[英]How to get the type of a variable using reflection c#
我一直在尋找 - 我找不到一個有效的答案......
我只是試圖使用反射找出類中的變量或屬性的類型...
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];
}
游戲是通過linq生成的類...我只是想得到字段的類型,所以我知道我是否需要投射我的xml item.value ....
要獲取字段的屬性值,請使用FieldInfo類FieldType屬性
foreach (FieldInfo fieldInfo in typeof(A).GetFields(BindingFlags.Instance |
BindingFlags.Static |
BindingFlags.NonPublic |
BindingFlags.Public))
{
Console.WriteLine(fieldInfo.FieldType.Name);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.