Reputation: 13
I have been looking for a while - and I cant find an answer that works....
I am just trying to to find out the type of a variable or property in a class using reflection...
foreach (XElement items in nodes)
{
Game newGame = new Game();
FieldInfo[] fields = newGame.GetType().GetFields(BindingFlags.Instance |
BindingFlags.Static |
BindingFlags.NonPublic |
BindingFlags.Public);
foreach(XAttribute item in items.Attributes())
{
foreach (FieldInfo f in fields)
{
if (f.Name.Remove(0,1) == item.Name.LocalName)
{
if (GetTypeOrUnderlyingType(f) == typeof(Int32))
{
Type type = typeof(Int32).DeclaringType;
f.SetValue(newGame, Convert.ChangeType(item.Value, type));
}
}
}
}
}
public Type GetTypeOrUnderlyingType(object o)
{
Type type = o.GetType();
if (!type.IsGenericType) { return type; }
return type.GetGenericArguments()[0];
}
And Game is a generated class via linq... I just want to get the type of the field so I know whether i need to cast my xml item.value....
Upvotes: 0
Views: 2246
Reputation: 7443
To get the property value of the field use the FieldInfo classes FieldType property
foreach (FieldInfo fieldInfo in typeof(A).GetFields(BindingFlags.Instance |
BindingFlags.Static |
BindingFlags.NonPublic |
BindingFlags.Public))
{
Console.WriteLine(fieldInfo.FieldType.Name);
}
Upvotes: 2