我有三个课程:
public class TestA
{
public string Str1 { get; set; }
public string Str2 { get; set; }
public TestB TestB { get; set; }
public TestA()
{
Str1 = "string1";
Str2 = "string2";
TestB = new TestB();
}
}
public class TestB
{
public string Str3 { get; set; }
public string Str4 { get; set; }
public TestC ObjTestC { get; set; }
public TestB()
{
Str3 = "string3";
Str4 = "string4";
ObjTestC = new TestC();
}
}
public class TestC
{
public string Str5 { get; set; }
public TestC()
{
Str5 = "string5";
}
}
现在,我得到了所有的 PropertyInfo 并创建了一个新对象:
//Get all the properties
var prop = typeof(TestA).GetProperties();
for (int i = 0; i < prop.Count(); i++)
{
var propertyInfo = prop[i];
if (propertyInfo.PropertyType.Namespace != "System")
{
if (propertyInfo.PropertyType.IsGenericType &&
propertyInfo.PropertyType.GetGenericTypeDefinition() == typeof(List<>))
{
Type itemType = propertyInfo.PropertyType.GetGenericArguments()[0]; // use this...
var listObjectProperties = itemType.GetProperties();
prop = prop.Union(listObjectProperties).ToArray();
}
else
{
var childProp = propertyInfo.PropertyType.GetProperties();
prop = prop.Union(childProp).ToArray();
}
}
}
//Create Object
TestA testA = new TestA();
现在,我需要调用每个属性的 getter 方法。我尝试了以下调用 TestA 类的属性的 getter。但是,在尝试调用 TestB 和 TestC 中的属性获取器时会引发错误:
// Loop through all properties
foreach (PropertyInfo propertyInfo in prop)
{
MethodInfo getterMethodInfo = propertyInfo.GetGetMethod();
var obj=getterMethodInfo.Invoke(testA, null);
}
请帮忙...
提前致谢