如何在反射中判断属性类型是否为集合?

6
List<MyClass> MyClassPro
{
   get;set;
}

MyClass obj = new MyClass();

obj.MyClassPro = null;

考虑 MyClassPro 为 null 的情况。在反射的情况下,我不会知道类名或属性名。
如果我尝试使用 GetType 来获取属性的类型,如下所示:
      Type t = obj.GetType();

它返回的是 "System.Collections.Generic.list",但我的期望是得到类型为 MyClass。

我还尝试了以下方式:

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

由于集合属性的值为空,因此返回错误,我们无法获取类型。

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

请帮助我!

提前感谢您。


你能否澄清一下,看起来好像无法编译。 - Gustavo Mori
这不是完整的代码。只需假设情况并给我答案即可。 - Thaadikkaaran
2个回答

11

使用 propertyInfo.PropertyType 替代 propertyInfo.GetValue(obj,null).GetType(),这样可以获取属性的类型,即使属性值为 null

因此,当您有一个类似于以下的类时:

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

如果有一个名为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];

这将在typeArg中返回值System.String(作为System.Type实例)。


是的,它返回System.Collections.Generic.List。我需要属性的类型而不是集合。 - Thaadikkaaran
你应该能够像你自己的代码示例中那样,在propertyInfo.PropertyType上调用"GetGenericArguments().First()"。 - Chaquotay
是的,我调用了它。它返回了System.Collections.Generic.List。 - Thaadikkaaran
我添加了一个例子,应该可以澄清我的意思。 - Chaquotay

6

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

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

我使用了你建议的方法。但是如果集合属性为空,我想要获取类型。 - Thaadikkaaran
我相信你首先为类创建构造函数。 构造函数() { List<MyClassPro> dd = new List<MyClassPro>(); dd = null; } - hashi

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接