기본값으로 객체 속성을 채우는 것입니다
-
20-09-2019 - |
문제
더미 데이터로 객체의 속성을 채우고 싶습니다. 여기 내 코드가 있지만 항상 NULL을 반환합니다.
private static object InsertDummyValues(object obj)
{
if (obj != null)
{
var properties = obj.GetType().GetProperties(BindingFlags.Instance | BindingFlags.DeclaredOnly | BindingFlags.Public);
foreach (var property in properties)
{
if (property.PropertyType == typeof (String))
{
property.SetValue(obj, property.Name.ToString(), null);
}
else if (property.PropertyType == typeof(Boolean))
{
property.SetValue(obj, true, null);
}
else if (property.PropertyType == typeof(Decimal))
{
property.SetValue(obj, 23.5, null);
}
else
{
// create the object
var o = Activator.CreateInstance(Type.GetType(property.PropertyType.Name));
property.SetValue(obj,o,null);
if (o != null)
return InsertDummyValues(o);
}
}
}
return obj;
}
해결책
당신은 그것을 말했습니다 return null;
, 노력하다 return obj;
대신에.
또한 제거하십시오 return
~로부터 if (o != null) return InsertDummyValues(o);
선.
의견에 귀하의 질문에 답하기 위해 ...
else if (property.PropertyType.IsArray)
{
property.SetValue(obj, Array.CreateInstance(type.GetElementType(), 0), null);
}
다른 팁
당신은 누락되었습니다 return obj;
의 끝에서 if (obj != null)
차단하다...
제휴하지 않습니다 StackOverflow