C# 使用methodInfo.Invoke将列表作为输出参数返回
我试图使用反射从动态调用的方法返回一个集合作为out参数。我面临的问题是,我无法从该方法获取更新的集合。请在下面找到代码片段C# 使用methodInfo.Invoke将列表作为输出参数返回,c#,reflection,C#,Reflection,我试图使用反射从动态调用的方法返回一个集合作为out参数。我面临的问题是,我无法从该方法获取更新的集合。请在下面找到代码片段 protected void Page_Load(object sender, EventArgs e) { Run(); } public void Run() { //Dictionary - this is for further Dictionary<string, object> xmlArgs = new Diction
protected void Page_Load(object sender, EventArgs e)
{
Run();
}
public void Run()
{
//Dictionary - this is for further
Dictionary<string, object> xmlArgs = new Dictionary<string, object>();
Employee def = new Employee(10, 10000);
xmlArgs["SalaryLimit"] = 2000;
xmlArgs["Employee"] = new List<Employee> { def };
//Create Instance of the method
MethodInfo mi = this.GetType().GetMethod("GetEmployee");
// Adding parameters
List<object> args = new List<object>();
foreach (ParameterInfo pi in mi.GetParameters())
{
args.Add(xmlArgs[pi.Name]);
}
//Invoke
mi.Invoke(this, args.ToArray());
//The collect is not updated below . ????
List<Employee> filter = (List<Employee>)args[1];
}
public List<Employee> GetEmployee(int SalaryLimit, out List<Employee> Employee)
{
List<Employee> objEmpList = new List<Employee>();
objEmpList.Add(new Employee(1, 1000));
objEmpList.Add(new Employee(2, 2000));
objEmpList.Add(new Employee(3, 3000));
objEmpList.Add(new Employee(4, 4000));
objEmpList.Add(new Employee(5, 5000));
Employee = objEmpList.Where(x => x.Salary > SalaryLimit).ToList();
return objEmpList;
}
}
public class Employee
{
public Employee() { }
public Employee(int Id, int Salary)
{
this.Id = Id;
this.Salary = Salary;
}
public int Id { get; set; }
public int Salary { get; set; }
}
受保护的无效页面加载(对象发送方,事件参数e)
{
Run();
}
公开募捐
{
//字典-这是为了进一步了解
Dictionary xmlArgs=新字典();
员工定义=新员工(101000);
xmlArgs[“SalaryLimit”]=2000;
xmlArgs[“Employee”]=新列表{def};
//创建方法的实例
MethodInfo mi=this.GetType().GetMethod(“GetEmployee”);
//添加参数
列表参数=新列表();
foreach(mi.GetParameters()中的ParameterInfo pi)
{
Add(xmlArgs[pi.Name]);
}
//援引
调用(this,args.ToArray());
//下面的收集未更新????
列表过滤器=(列表)参数[1];
}
公共列表GetEmployee(int SalaryLimit,out List Employee)
{
List objEmpList=新列表();
对象列表添加(新员工(11000人));
对象列表添加(新员工(22000));
对象列表添加(新员工(33000));
对象列表添加(新员工(44000));
对象列表添加(新员工(55000));
Employee=objEmpList.Where(x=>x.Salary>SalaryLimit.ToList();
返回对象列表;
}
}
公营雇员
{
公共雇员(){}
公共雇员(内部Id,内部工资)
{
这个.Id=Id;
这个。薪水=薪水;
}
公共int Id{get;set;}
公共整数{get;set;}
}
问题在于:
mi.Invoke(this, args.ToArray());
//The collect is not updated below . ????
List<Employee> filter = (List<Employee>)args[1];
请注意,您也不需要将对象放在输出位置(它不会造成任何伤害,但会在数组中被覆盖)。当您知道类型和方法名称时,为什么要使用反射?可能是在调用
mi.Invoke(this,args.ToArray());'
IEnumerable.ToArray()`方法返回一个新的数组对象,该对象的引用被传递给Invoke方法,而不是原始的args
集合,并且是对数组的引用被更新为输出,而不是原始列表?可能是
object[] args2 = args.ToArray();
mi.Invoke(this, args2);
List<Employee> filter = (List<Employee>)args2[1]; // pull the output form the _array_, not the _list_.