Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 通过反射获取列表_C#_List_Reflection - Fatal编程技术网

C# 通过反射获取列表

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;/

我有一个类,它包含一个类型为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;//注意“作为…”
//由于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>;