Are there any shortcuts/easier(VB) style way for raising events in C#?
Example in VB I have a worker class
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
and wire them up in another class with
AddHandler _worker.EventNumber1, AddressOf EventNumber1Handler
AddHandler _worker.EventNumber2, AddressOf EventNumber2Handler
and in C# the worker class
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");
}
}
and wire that up with
worker.EventNumber1 += new Worker.EventNumber1Handler(worker_EventNumber1);
worker.EventNumber2 += new Worker.EventNumber2Handler(worker_EventNumber2);
So I guess my question is do I always need to add the delegate along with the event in c#? Is there any new syntax for c# 3.0/4.0?
Regards
_Eric
And then there is the strong recommendation that an event should always have the signature:
delegate void MyEvent(objectr sender, MyEventArgs e);
So you would also have to write a class deriving from EventArgs to encapsulate your Dictionary.
The good news is that you can usually get away with the EventHandler<> and Action<> classes.
public event Action<Dictionary<int,string>> EventNumber1;
精彩评论