c# – 如果属性是反射中的集合,如何知道属性的类型?
发布时间:2020-12-15 18:21:05 所属栏目:百科 来源:网络整理
导读:ListMyClass MyClassPro{ get;set;}MyClass obj = new MyClass();obj.MyClassPro = null; 考虑MyClassPro为null.在反思的情况下,我不会知道类名或属性名称. 如果我尝试使用GetType获取属性类型, Type t = obj.GetType(); 它返回“System.Collections.Generic
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实例). (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |