I have this class:
internal class MyClass
{
string name { get; set; }
List<MyClass2> myClass2 { get; set; }
}
where MyClass2:
internal MyClass2
{
string field1 { get; set; }
string field2 { get; set; }
int field3 { get; set; }
long field4 { get; set; }
}
I want to retrieve the fields of the myClass2 via reflection, so I coded the snippet below:
Type objectType = typeof(MyClass);
IEnumerable<MemberInfo> members = objectType
.GetMembers(BindingFlags.NonPublic | BindingFlags.Instance)
.Where(p => p.MemberType == MemberTypes.Property);
foreach (var field in members)
{
if (field.Name != "name")
{
var fieldT = field.GetType();
Console.WriteLine("Field: " + field.Name + "; Field type: " + typeof(Property));
Type propertiesType = field.GetType();
IEnumerable<MemberInfo> propertiesMembers = typeof(Property)
.GetMembers(BindingFlags.NonPublic | BindingFlags.Instance)
.Where(p => p.MemberType == MemberTypes.Property);
foreach(var property in propertiesMembers)
{
Console.WriteLine("Looking for field: " + field.Name);
var value = fields.Where(f => f.Key == field.Name).First();
Console.WriteLine("Actual value receiver for: " + field.Name + " => " + value);
}
}
}
where fields it's just a Dictionary<string, dynamic> containing non interesting data for the question.
The thing is that I am unable to retrieve the fields in the variable myClass2, first, because it's a collection, and second, because in the fields variable of the loop, it's determining it's type to System.Reflection.RuntimePropertyInfo.
How can I modify my code to get a collection of the fields inside myClass2, yielding the real data that I am looking for? That is just the member info for the MemberTypes that are MemberTypes.Property?
Thanks.