如果属性是反射中的集合,如何知道它的类型?

Tha*_*ran 6 c# reflection

List<MyClass> MyClassPro
{
   get;set;
}

MyClass obj = new MyClass();

obj.MyClassPro = null;
Run Code Online (Sandbox Code Playgroud)

考虑MyClassPro为null.在反思的情况下,我不会知道类名或属性名称.

如果我尝试使用GetType获取属性类型,

      Type t = obj.GetType();
Run Code Online (Sandbox Code Playgroud)

它返回"System.Collections.Generic.list.但我的期望是将Type作为MyClass.

我也试过这样的方式

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

但它返回错误是因为collection属性的值为null所以我们无法得到Type.

在这种情况下,我如何获得集合属性的类型.

请帮我 !

提前致谢.

Cha*_*tay 11

即使属性值为,使用propertyInfo.PropertyType而不是propertyInfo.GetValue(obj,null).GetType()应该为您提供属性类型null.

所以当你有一个类的时候

public class Foo {
    public List<string> MyProperty { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

和实例Foo中obj,然后

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

会给你价值System.String(作为一个System.Type实例)typeArg.


has*_*shi 6

使用propertyInfo.PropertyType具有名称的属性IsGenericType,例如:

if (propertyInfo.PropertyType.IsGenericType)
{
    // code ...
}
Run Code Online (Sandbox Code Playgroud)