将函数从另一个类分配给事件处理程序

时间:2017-04-01 01:12:29

标签: c# .net-3.5

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

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

我希望修复最后3个类(在dll中使用它们)并且仅从我使用dll的位置更改class0。

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

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

此事件应由class3的对象响应。这些课程之间存在关系。

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

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

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

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>,但如果我直接在其中定义它,我可以为EventHandler分配一个公共void函数class3.cs。

如果我对问题的描述令人困惑,我道歉。我觉得我的脑细胞纠缠在一起。

1 个答案:

答案 0 :(得分:0)

按照@Peter的建议,解决这个问题相当容易。首先,我更改了Func<Object,EventArg>的{​​{1}}参数。然后我将活动订阅从Action<Object,EventArg>更改为OnCall += callStart;

在此问题的示例中,生成的代码为:

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