[英]How to know the Type of a Property if it is collection in 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。
在这种情况下,我如何获得集合属性的类型。
请帮我 !
提前致谢。
使用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
实例)。
使用propertyInfo.PropertyType
,它具有名称为IsGenericType
属性,例如:
if (propertyInfo.PropertyType.IsGenericType)
{
// code ...
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.