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

标签 c# reflection

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();
             }
        }

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

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

请帮帮我!

提前致谢。

最佳答案

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

所以当你有一个类似的类

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 实例)。

关于c# - 如果它是反射中的集合,如何知道属性的类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6027216/

相关文章:

c# - 如何在 DynamicProxy 类中使​​用自定义属性

.net - 在非当前 AppDomain 上使用 DefineDynamicAssembly 动态创建程序集时出现异常

java - 从子类外部访问父类的 protected 方法(使用反射或任何可行的方法)

c# - 按名称调用类或选择案例/开关?

c# - 如何使用 OpenSSL.Net C# 包装器通过 AES 加密字符串?

c# - 如何确定类是否在构建或运行时用 PostSharp 方面进行修饰

c# - 无需安装的 C++ 数据库访问

c# - 索引器是否应该始终引用离散序列?

c# - 如何在可视化树中查找元素? wp7

Java - java.lang.NoSuchMethodException