将另一个 class 的函数分配给事件处理程序

Assigning a function from another class to an event handler

考虑以下情况。我在不同的 cs 文件中有 4 classes:

class0.cs
class1.cs
class2.cs
class3.cs

我希望修复最后 3 个 classes(在 dll 中使用它们)并且只更改我使用 dll 的 class0。

所以在class0中我想定义一个事件发生时会执行的函数。例如:

public void callStart(Object x, EventArg e){...}

此事件应由 class3 的对象响应。这个class之间有关系。

class0 use an instance of class1
class1 use an instance of class2
class2 use an instance of class3

所以我的计划是将函数 callStart 作为构造函数的参数传递,这样它就可以到达 class3:

的对象

所以每个 class 的构造函数是这样的:

public class1(...., Func<Object,EventArg> callStart){
...
c2 = new class2(..., callStart);
}

public class2(...., Func<Object,EventArg> callStart){
...
c3 = new class3(..., callStart);
}

public class3(...., Func<Object,EventArg> callStart){...

OnCall += callStart;
}

Visual Studio 2015 中的编译器告诉我 Func<Object,EventArg> 不能变成 EventHandler<EventArg>,但我可以将 public void 函数分配给EventHandler 如果我直接定义在class3.cs.

如果我对问题的描述令人困惑,我深表歉意。感觉脑细胞都纠结了

根据@Peter 的建议,这个问题很容易解决。首先,我将 Func<Object,EventArg> 参数更改为 Action<Object,EventArg>。然后我将事件订阅从 OnCall += callStart; 更改为 OnCall += (sender, e) => callStart(sender, e);.

在这个问题的例子中,结果代码是:

public class1(...., Action<Object,EventArg> callStart){
...
c2 = new class2(..., callStart);
}

public class2(...., Action<Object,EventArg> callStart){
...
c3 = new class3(..., callStart);
}

public class3(...., Action<Object,EventArg> callStart){...

OnCall += (sender, e) => callStart(sender, e);
}