简体   繁体   中英

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....

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);
                }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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