【问题标题】:Returning a list as output parameter using methodInfo.Invoke使用 methodInfo.Invoke 返回一个列表作为输出参数
【发布时间】:2014-07-16 23:00:09
【问题描述】:

我正在尝试使用反射从动态调用的方法返回一个集合作为输出参数。我面临的问题是我无法从方法中获取更新的集合。请在下面找到代码sn-p

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

【问题讨论】:

  • 知道类型和方法名为什么还要使用反射?
  • 会不会是在你调用mi.Invoke(this, args.ToArray());' the IEnumerable.ToArray()`方法的那一行返回一个新的数组对象,它的引用被传递给Invoke方法,不是 原始的args 集合,它是对作为输出而不是原始列表更新的数组的引用?

标签: c# reflection


【解决方案1】:

问题出在这里:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-02-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-24
    • 2017-06-12
    • 2011-01-14
    相关资源
    最近更新 更多