我有三个类:
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的属性getter时,它会抛出错误:
// Loop through all properties
foreach (PropertyInfo propertyInfo in prop)
{
MethodInfo getterMethodInfo = propertyInfo.GetGetMethod();
var obj=getterMethodInfo.Invoke(testA, null);
}
帮我一个忙...
提前感谢您