问题描述
|
我有下一个代码:
public class MyClass
{
object field1;
object field2;
}
///////
List<MyClass> lst = new List<MyClass>();
GetLstMember(lst,\"field1\");
///////
List<object> GetLstMember(List<Object> lst,string memberName)
{
List<object> rezult = new List<object>();
for(int i=0; i<lst.Count; i++)
{
rezult.Add(lst[i].GetType().InvokeMember(
memberName,BindingFlag.GetProperty,null,lst[i],null);
}
return rezult;
}
是否有其他方法可以在不使用反射的情况下编写方法GetLstMember
?我尝试使用BindingSource
没有成功:
BindingSource bs = new BindingSource(lst,memberName);
return bs.List;
好的,我知道可以使用反射了。此类代码与以前的代码在性能上是否有所不同:
List<object> GetLstMember(List<Object> lst,string memberName)
{
List<object> rezult = new List<object>();
for (int i = 0; i < lst.Count; i++)
rezult.Add(lst[i].GetType().GetProperty(memberName).GetValue(lst[i],null)**);
return rezult;
}
解决方法
这是唯一的方法;这就是反思的目的。
即使使用BindingList,它也会使用反射。
另外,BindingList实际上不能这样做。
, 如果您在.net 4上运行,则可以使用dynamic关键字。 http://msdn.microsoft.com/en-us/library/dd264736.aspx
这样的事情应该起作用。
public class MyClass {
object field1;
object field2;
}
///////
List<MyClass> lst = new List<MyClass>();
GetLstMember(lst);
///////
List<object> GetLstMember(List<dynamic> lst,string memberName)
{
List<object> rezult=new List<object>();
for(int i=0;i<lst.Count;i++){
switch(memberName){
case \"field1\":
rezult.Add(lst[i].field1);
break;
case \"field2\":
rezult.Add(lst[i].field2);
break;
}
}
return rezult;
}
, 因此,在
lst[i].GetType().GetProperty(memberName).GetValue(lst[i],null)
lst[i].GetType().InvokeMember(memberName,BindingFlag.GetProperty,null,lst[i],null)
?