开发者

How to encapsulate event type member in c#?

I can create getter and setter for an int member. How to do this if this member is an event type ?

Update: I want to call another method each 开发者_Go百科time this member is set.


You can implement custom event accessors.

Example:

public delegate int DoSomething();
private event DoSomething _somethingHappened;
public event DoSomething SomethingHappened
{
  add { _somethingHappened += value; }
  remove { _somethingHappened -= value; }
}


Events are in fact ready for consumption, put very simply, declaring an event is actually defining a getter/setter for the underlying delegate and it is therefore not necessary to define explicit getter/setter.

If you want to do some kind of custom handling for the attach/detach of handlers to the event then you can take a look at the following MSDN documentation

http://msdn.microsoft.com/en-us/library/bb882534.aspx

http://msdn.microsoft.com/en-us/library/z4ka55h8.aspx


Events are declared using a delegate type - simply make your property the delegate type.

From MSDN:

In the .NET Framework class library, events are based on the EventHandler delegate and the EventArgs base class.

public EventHandler MyEvent {get; set;}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜