如何知道属性的类型(如果它是反射中的集合)
本文关键字:反射 集合 如果 何知道 属性 类型 | 更新日期: 2023-09-27 17:56:54
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,因此我们无法获取 Type。
在这种情况下,我如何获取集合属性的类型。
请帮助我!
提前谢谢。
使用 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
实例)。
使用具有名称为 IsGenericType
的属性的propertyInfo.PropertyType
,例如:
if (propertyInfo.PropertyType.IsGenericType)
{
// code ...
}