I have got three classes:
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";
}
}
Now, I have got all the PropertyInfo and created a new object:
//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();
Now, what I need is to invoke the getter method of each property. I tried the following which invokes the getter of the properties of the TestA class. But, it is throwing error when trying to invoke the getter of properties in TestB and TestC:
// Loop through all properties
foreach (PropertyInfo propertyInfo in prop)
{
MethodInfo getterMethodInfo = propertyInfo.GetGetMethod();
var obj=getterMethodInfo.Invoke(testA, null);
}
Please help...
Thanks in advance