简体   繁体   中英

How to know the Type of a Property if it is collection in Reflection?

List<MyClass> MyClassPro
{
   get;set;
}

MyClass obj = new MyClass();

obj.MyClassPro = null;

Consider the MyClassPro is null. In situation of Reflection i wont be knowing the Classname or Property Name.

If i try to get the Type of property using GetType like ,

      Type t = obj.GetType();

It is returning "System.Collections.Generic.list. But my expectation is to get the Type as MyClass.

I also tried the way like

        foreach(PropertyInfo propertyInfo in obj.GetProperties())
        {
             if(propertyInfo.IsGenericType)
             {
              Type t = propertyInfo.GetValue(obj,null).GetType().GetGenericArguments().First();
             }
        }

But it is returning error because of the Value of the collection property is null so we cant get the Type.

In this situation how can i get the Type of a collection Property.

Please help me !

Thanks in Advance.

Use propertyInfo.PropertyType instead of propertyInfo.GetValue(obj,null).GetType() which should give you the property type even if the property value is null .

So when you have a class like

public class Foo {
    public List<string> MyProperty { get; set; }
}

and an instance of Foo in obj , then

var propertyInfo = obj.GetType().GetProperty("MyProperty"); // or find it in a loop like in your own example
var typeArg = propertyInfo.PropertyType.GetGenericArguments()[0];

will give you the value System.String (as a System.Type instance) in typeArg .

Use propertyInfo.PropertyType which has property with name IsGenericType , eg:

if (propertyInfo.PropertyType.IsGenericType)
{
    // code ...
}

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