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

时间:2011-05-17 06:46:16

标签: c# reflection

List<MyClass> MyClassPro
{
   get;set;
}

MyClass obj = new MyClass();

obj.MyClassPro = null;

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

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

      Type t = obj.GetType();

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

我也试过像

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

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

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

请帮助我!

先谢谢。

2 个答案:

答案 0 :(得分:11)

使用propertyInfo.PropertyType代替propertyInfo.GetValue(obj,null).GetType(),即使属性值为null,也应该为您提供属性类型。

所以当你有一个像

这样的课程时
public class Foo {
    public List<string> MyProperty { get; set; }
}

以及Fooobj的实例,然后

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

会在System.String中为您提供值System.Type(作为typeArg个实例)。

答案 1 :(得分:6)

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

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