81 lines
1.4 KiB
Plaintext
81 lines
1.4 KiB
Plaintext
Since .Net Framework version 2.0 it is not necessary to declare a delegate that specifies a class derived from ``++System.EventArgs++``. The ``++System.EventHandler<TEventArgs>++`` delegate mechanism should be used instead as it allows any class derived from ``++EventArgs++`` to be used with that handler.
|
|
|
|
|
|
This rule raises an issue when an old style delegate is used as an event handler.
|
|
|
|
|
|
== Noncompliant Code Example
|
|
|
|
[source,text]
|
|
----
|
|
public class MyEventArgs : EventArgs
|
|
{
|
|
}
|
|
|
|
public delegate void MyEventHandler(object sender, MyEventArgs e); // Noncompliant
|
|
|
|
public class EventProducer
|
|
{
|
|
public event MyEventHandler MyEvent;
|
|
|
|
protected virtual void OnMyEvent(MyEventArgs e)
|
|
{
|
|
if (MyEvent != null)
|
|
{
|
|
MyEvent(e);
|
|
}
|
|
}
|
|
}
|
|
|
|
public class EventConsumer
|
|
{
|
|
public EventConsumer(EventProducer producer)
|
|
{
|
|
producer.MyEvent += HandleEvent;
|
|
}
|
|
|
|
private void HandleEvent(object sender, MyEventArgs e)
|
|
{
|
|
// Do something...
|
|
}
|
|
}
|
|
----
|
|
|
|
|
|
== Compliant Solution
|
|
|
|
[source,text]
|
|
----
|
|
public class MyEventArgs : EventArgs
|
|
{
|
|
}
|
|
|
|
public class EventProducer
|
|
{
|
|
public event EventHandler<MyEventArgs> MyEvent;
|
|
|
|
protected virtual void OnMyEvent(MyEventArgs e)
|
|
{
|
|
if (MyEvent != null)
|
|
{
|
|
MyEvent(e);
|
|
}
|
|
}
|
|
}
|
|
|
|
public class EventConsumer
|
|
{
|
|
public EventConsumer(EventProducer producer)
|
|
{
|
|
producer.MyEvent += HandleEvent;
|
|
}
|
|
|
|
private void HandleEvent(object sender, MyEventArgs e)
|
|
{
|
|
// Do something...
|
|
}
|
|
}
|
|
----
|
|
|
|
|