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

时间:2014-07-16 14:53:44

标签: 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 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; }
}

1 个答案:

答案 0 :(得分:2)

问题在于:

    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_.

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