【问题标题】:How to know the Type of a Property if it is collection in Reflection?如果它是反射中的集合,如何知道属性的类型?
【发布时间】:2011-05-17 06:46:15
【问题描述】:
List<MyClass> MyClassPro
{
   get;set;
}

MyClass obj = new MyClass();

obj.MyClassPro = null;

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

如果我尝试使用 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();
             }
        }

但它返回错误,因为集合属性的值为 null,所以我们无法获取类型。

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

请帮帮我!

提前致谢。

【问题讨论】:

  • 您能否澄清一下,它看起来不会编译。
  • 它不是一个完整的代码。假设情况,请给我答案。

标签: c# reflection


【解决方案1】:

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

所以当你有类似的课程时

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

然后是obj 中的Foo 实例

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。我需要属性的类型而不是集合。
  • 您应该可以像在您自己的代码示例中一样在propertyInfo.PropertyType 上调用GetGenericArguments().First()
  • 是的,我打过电话。它返回 System.Collections.Generic.List。
  • 我添加了一个示例,应该可以阐明我的意思。
【解决方案2】:

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

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

【讨论】:

  • 我使用了你的建议。但是如果集合属性为空,我想获取类型。
  • 我相信您首先为班级创建了承包商。承包商 () { List dd = new List(); dd = null; }
猜你喜欢
  • 2011-07-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-04-02
  • 1970-01-01
  • 2014-04-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多