使用反射自动创建代表列表

Using Reflection to create automatically a List of Delegates

我有一个名为 Operations.cs 的 Class,使用某种方法。我想创建一个代表列表来随机选择一个方法。现在我有以下工作解决方案:

public delegate void Delmethod(ExampleClass supervisor);
public static Operations op = new Operations();
public List<Delmethod> opList = new List<Delmethod>();

opList.Add(op.OpOne);
opList.Add(op.OpTwo);
opList.Add(op.OpThree);
opList.Add(op.OpFour);
opList.Add(op.OpFive);
opList.Add(op.OpSix);
opList.Add(op.OpSeven);

但我真正想要的是在 Operations.cs 中添加新方法时自动生成 List opList。我试图使用反射来尝试解决我的问题,如下所示:

List<MethodInfo> listMethods = new List<MethodInfo>(op.GetType().GetMethods().ToList());

foreach (MethodInfo meth in listMethods)
{
   opList.Add(meth);
}

我认为这行不通,因为我混淆了委托的含义,但我没有想法。

您必须根据特定方法信息创建委托。 假设 Operations 只有 public 个具有相同签名的实例方法,代码将如下所示:

public static Operations op = new Operations();
public List<Action<ExampleClass>> opList = new List<Action<ExampleClass>>();

oplist.AddRange(op
    .GetType()
    .GetMethods()
    .Select(methodInfo => (Action<ExampleClass>)Delegate.CreateDelegate(typeof(Action<ExampleClass>), op, methodInfo)));

请注意,您无需声明 Delmethod,因为有 Action<T>.