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/