简体   繁体   English

如何使用反射c#获取变量的类型

[英]How to get the type of a variable using reflection c#

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.... 游戏是通过linq生成的类...我只是想得到字段的类型,所以我知道我是否需要投射我的xml item.value ....

To get the property value of the field use the FieldInfo classes FieldType property 要获取字段的属性值,请使用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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM