RE: Delegates/events
- From: jetan@xxxxxxxxxxxxxxxxxxxx ("Jeffrey Tan[MSFT]")
- Date: Mon, 26 Mar 2007 08:26:34 GMT
Hi Peter ,
In "AMethod", the parameter "callback" is of type
"EventHandler<EventArgs>", which is a delegate instead of event. So you can
not pass an event to this method. You should explicitly construct a
"EventHandler<EventArgs>" delegate(which must explictly wrap a method) and
pass this delegate to the method, like this:
public class First
{
public event EventHandler<EventArgs> MyEvent;
public void OnMyEvent(object sender, EventArgs args)
{
if (this.MyEvent != null)
this.MyEvent(sender, args);
}
}
public class Second
{
public void Method(First aInstance)
{
Third th = new Third();
EventHandler<EventArgs> EH = new
EventHandler<EventArgs>(aInstance.OnMyEvent);
th.AMethod(EH);
}
}
public class Third
{
public void AMethod(EventHandler<EventArgs> callback)
{
if (callback != null)
callback(this, new EventArgs());
}
}
Additionally, the code snippet provided by "PS" is almost the same as this,
but it uses an implicit way of constructing "EventHandler<EventArgs>". That
is when passing "aInstance.OnMyEvent" to the method, the C# compiler will
emit an explicit construct to "EventHandler<EventArgs>" delegate like below:
public void Method(Form1.First aInstance)
{
Form1.Third th = new Form1.Third();
th.AMethod(new EventHandler<EventArgs>(aInstance.OnMyEvent));
}
Hope this helps.
Best regards,
Jeffrey Tan
Microsoft Online Community Support
==================================================
Get notification to my posts through email? Please refer to
http://msdn.microsoft.com/subscriptions/managednewsgroups/default.aspx#notif
ications.
Note: The MSDN Managed Newsgroup support offering is for non-urgent issues
where an initial response from the community or a Microsoft Support
Engineer within 1 business day is acceptable. Please note that each follow
up response may take approximately 2 business days as the support
professional working with you may need further investigation to reach the
most efficient resolution. The offering is not appropriate for situations
that require urgent, real-time or phone-based interactions or complex
project analysis and dump analysis issues. Issues of this nature are best
handled working with a dedicated Microsoft Support Engineer by contacting
Microsoft Customer Support Services (CSS) at
http://msdn.microsoft.com/subscriptions/support/default.aspx.
==================================================
This posting is provided "AS IS" with no warranties, and confers no rights.
.
- References:
- Delegates/events
- From: Peter Larsen []
- Delegates/events
- Prev by Date: Re: Recommendation on How to build a long string
- Next by Date: Re: delegates and events
- Previous by thread: Re: Delegates/events
- Next by thread: RE: Delegates/events
- Index(es):
Relevant Pages
|