VB中的示例我有一个工人类
Public Class worker
Public Event EventNumber1(ByVal messages As Dictionary(Of Integer, String))
Public Event EventNumber2(ByVal message As String)
Public Sub CallEventNumber1()
Dim dict As New Dictionary(Of Integer, String)
dict.Add(1, "EventNumber1 First message")
dict.Add(2, "EventNumber1 Second message")
RaiseEvent EventNumber1(dict)
End Sub
Public Sub CallEventNumber2()
RaiseEvent EventNumber2("I am an EventNumber2 Message")
End Sub
End Class
并使用
将它们连接到另一个班级AddHandler _worker.EventNumber1, AddressOf EventNumber1Handler
AddHandler _worker.EventNumber2, AddressOf EventNumber2Handler
和C#中的工人类
class Worker
{
public delegate void EventNumber1Handler(Dictionary<int, string> messages);
public delegate void EventNumber2Handler(string message);
public event EventNumber1Handler EventNumber1;
public event EventNumber2Handler EventNumber2;
public void CallEventNumber1()
{
Dictionary<int, string> dict = new Dictionary<int, string>();
dict.Add(1, "EventNumber1 First message");
dict.Add(2, "EventNumber1 Second message");
if (EventNumber1 != null)
EventNumber1(dict);
}
public void CallEventNumber2()
{
if (EventNumber2 != null)
EventNumber2("I am an EventNumber2 Message");
}
}
并用
连接worker.EventNumber1 += new Worker.EventNumber1Handler(worker_EventNumber1);
worker.EventNumber2 += new Worker.EventNumber2Handler(worker_EventNumber2);
所以我想我的问题是我是否总是需要在c#中添加委托和事件?是否有c#3.0 / 4.0的新语法?
此致
_Eric
答案 0 :(得分:3)
然后强烈建议事件应始终具有签名:
delegate void MyEvent(objectr sender, MyEventArgs e);
因此,您还必须编写一个派生自EventArgs的类来封装您的Dictionary。
好消息是,您通常可以使用EventHandler&lt;&gt;和行动&lt;&gt;类。
public event Action<Dictionary<int,string>> EventNumber1;