【发布时间】: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());' theIEnumerable.ToArray()`方法的那一行返回一个新的数组对象,它的引用被传递给Invoke方法,不是 原始的args集合,它是对作为输出而不是原始列表更新的数组的引用?
标签: c# reflection