使用methodInfo.Invoke返回一个列表作为输出参数

本文关键字:列表 一个 参数 输出 Invoke methodInfo 返回 使用 | 更新日期: 2023-09-27 18:13:09

我试图使用反射从动态调用的方法返回一个集合作为输出参数。我面临的问题是,我无法从方法中获得更新的集合。请在

下面找到代码片段
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; }
}

使用methodInfo.Invoke返回一个列表作为输出参数

问题就在这里:

    mi.Invoke(this, args.ToArray());
    //The collect is not updated below . ????
    List<Employee> filter = (List<Employee>)args[1];

当您使用Invoke调用具有out参数的方法时-参数数组中的适当位置将被更新为新值。由于您内联调用ToArray(),因此您没有对传递给Invoke的实际数组的引用,只有用于创建数组的列表。尝试将代码更改为:

    object[] args2 = args.ToArray();
    mi.Invoke(this, args2);
    List<Employee> filter = (List<Employee>)args2[1];  // pull the output form the _array_, not the _list_.

请注意,您也不需要在输出位置有一个对象(它不会影响任何东西,但它将在数组中被覆盖)。