C# 通过反射获取列表
我有一个类,它包含一个类型为PropertyInfo的列表:C# 通过反射获取列表,c#,list,reflection,C#,List,Reflection,我有一个类,它包含一个类型为PropertyInfo的列表: public List<PropertyInfo> Properties {get; set;} 但如果我试着循环它: foreach (var thisProp in PropList) - I get an error. 那么,还有其他的方法吗 谢谢你必须投下: var PropList=P .GetType() .GetProperty(“属性”) .GetValue(P,null)作为IEnumerable;/
public List<PropertyInfo> Properties {get; set;}
但如果我试着循环它:
foreach (var thisProp in PropList) - I get an error.
那么,还有其他的方法吗
谢谢你必须投下:
var PropList=P
.GetType()
.GetProperty(“属性”)
.GetValue(P,null)作为IEnumerable;//注意“作为…”
//由于PropList是IEnumerable,所以可以循环使用它
foreach(在PropList中变为thisProp){
...
}
因为查看代码后,只有
GetValue(…)
返回object
,所以很明显
var PropList = P.GetType().GetProperty("Properties").GetValue(this, null)
不返回因其导致的ienumerable和错误。要解决此问题,您需要将其转换为Ienumerable
var PropList = P
.GetType()
.GetProperty("Properties")
.GetValue(this, null) as IEnumerable<PropertyInfo>;
var PropList=P
.GetType()
.GetProperty(“属性”)
.GetValue(this,null)作为IEnumerable;
发生了什么错误?您是否可以创建一个接口,将列表属性{get;set;}
作为成员,这样您就不需要反射了?它抛出了“非泛型类型'IEnumerable'不能与类型参数一起使用”error@Aleksa科贾迪诺维奇:似乎您应该使用System.Collections.Generic添加
您需要传入P
,而不是将this
传递到.GetValue
方法中,因为您希望获取P
对象的属性,而不是this
对象。@mayor:捕捉得好!复制+粘贴这个问题真是件坏事。
var PropList = P.GetType().GetProperty("Properties").GetValue(this, null)
var PropList = P
.GetType()
.GetProperty("Properties")
.GetValue(this, null) as IEnumerable<PropertyInfo>;