开发者

C# - Events Question

开发者 https://www.devze.com 2023-01-03 21:15 出处:网络
Can any C# object be set up such that an event can be tied t开发者_Python百科o it to fire when it\'s value changes? If so, how is this done? For example, let\'s take a very simple example. Say I have

Can any C# object be set up such that an event can be tied t开发者_Python百科o it to fire when it's value changes? If so, how is this done? For example, let's take a very simple example. Say I have a variable declared as follows:

int i;

Is it possible to create an event that fires any time the value of i changes?

Thanks.


Well, you can't change fields so that events are fired when the value changes.

On the other hand, you can easily make it so that when a property changes, an event is fired. Only the author of the class containing the property can do this, however1 - you can't attach an event to an arbitrary existing class.


1 A slight exception would be a virtual property, which could be overridden solely for the purpose of raising the event. That would be pretty rare though.


Have a look at the INotifyPropertyChanged interface that can be implemented by a class and called by - at least some of - its properties to notify listeners that some values changed.


Another option would be to use the Observer pattern.

Grz, Kris.


Take a look at the PropertyChangedEvent pattern.

0

精彩评论

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