C#:通过反射将通用多播委托分配给具有不同数量参数的操作

C#:通过反射将通用多播委托分配给具有不同数量参数的操作,c#,reflection,types,delegates,action,C#,Reflection,Types,Delegates,Action,在我的课堂上,有些代表都是动作域。例如: public Action<int> onDiceRolled; public Action<Turn, Round> onTurnEnded; 对于我的类中的每个操作字段,要设置可用于编译的委托,请执行以下操作: GetType().GetFields() .Where(field => field.FieldType.ToString().Contains("Action")) .ToL

在我的课堂上,有些代表都是动作域。例如:

public Action<int> onDiceRolled;
public Action<Turn, Round> onTurnEnded;

对于我的类中的每个操作字段,要设置可用于编译的委托,请执行以下操作:

GetType().GetFields()
   .Where(field => field.FieldType.ToString().Contains("Action"))
   .ToList()
   .ForEach(field =>
   {
       Type type = field.FieldType; // e.g. Action<Turn, Round>
        if (!type.IsGenericType)
           return;

       Type[] para = type.GetGenericArguments(); // in example cases: {int} or {Turn, Round}
       Expression<Action> x = () => Console.WriteLine(field.Name + " was called.");
       var action = Expression.Lambda(x.Body, para.Select(p => Expression.Parameter(p))).Compile();
       field.SetValue(this, action);
   });
GetType().GetFields()
.Where(field=>field.FieldType.ToString().Contains(“操作”))
托利斯先生()
.ForEach(字段=>
{
Type Type=field.FieldType;//例如操作
如果(!type.IsGenericType)
返回;
Type[]para=Type.GetGenericArguments();//在示例情况下:{int}或{Turn,Round}
表达式x=()=>Console.WriteLine(调用了field.Name+);
var action=Expression.Lambda(x.Body,para.Select(p=>Expression.Parameter(p))).Compile();
field.SetValue(此操作);
});

SetValue
不是
+=
的等价物,后者是
System.Delegate.combined
代表。感谢您提供的信息。到目前为止,我是否设置或添加代理并不重要。首先,类型必须匹配,因为如果不匹配,添加代理也将不起作用。因此,类型的问题仍然存在
onDiceRolled += (i) => Console.WriteLine("onDiceRolled was called.");
GetType().GetFields()
   .Where(field => field.FieldType.ToString().Contains("Action"))
   .ToList()
   .ForEach(field =>
   {
       Type type = field.FieldType; // e.g. Action<Turn, Round>
        if (!type.IsGenericType)
           return;

       Type[] para = type.GetGenericArguments(); // in example cases: {int} or {Turn, Round}
       Expression<Action> x = () => Console.WriteLine(field.Name + " was called.");
       var action = Expression.Lambda(x.Body, para.Select(p => Expression.Parameter(p))).Compile();
       field.SetValue(this, action);
   });