如何捕获成员变量的变化? (C#)
这似乎是该语言的基础知识,但我不明白这是如何在 .Net 中实现的。我在类中有一个成员变量,例如 bool _isCommited
。我希望每当 _isCommissed
为 true 时就会发生一些事情。像这样的事情:
//Whenever _isCommitted == true()
{
Foo()
}
基本上就像一个事件,但这里它是我的变量。怎样做?非常感谢..
This seems to be basics of the language, but I do not understand how is this accomplished in .Net. I have a member variable in a class, say a bool _isCommitted
. I want something to happen whenever _isCommitted
is true. Something like this:
//Whenever _isCommitted == true()
{
Foo()
}
Basically like an event, but here it is my variable. How to? Many thanks..
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这通常是通过属性和支持私有字段来完成的。您需要确保您只能通过该物业进入。
This is normally done through properties and a backing private field. You need to ensure you only ever access through the property.
在最基本的层面上,您可以在您的类中创建一个事件:
现在人们可以像这样订阅您的事件:
用户可以通过这种方式取消注册他的事件处理程序:
无论您决定更改变量,您都会跟进它:
这将呼叫所有在您的活动中注册了功能的人。
话虽如此,您可以做很多改进。首先,将 _isCommited 放入属性中,并在其 setter 中执行事件回调。这样,您就不会忘记调用处理程序。
此处了解有关事件的更多信息。
这足以让你继续前进。但是,如果您进一步深入研究 C# 框架,您将发现在 System.ComponentModel 命名空间内使用此事件框架的标准化方法。具体来说,接口
INotifyPropertyChanged
,它巧妙地与一个更通用的事件系统联系在一起,该系统也可以很好地与微软自己的一些技术(例如WPF)配合使用,允许GUI元素自动获取类的更改。 此处INotifyPropertyChanged 的更多信息>。At the most basic level, you can create an event in your class:
Now people can subscribe to your event like so:
A user can unregister his event handler this way:
And wherever you decide to change your variable, you will follow it up with:
This will call everyone who has registered a function with your event.
Having said this, there are plenty of improvements that you can do. First, make _isCommitted into a property, and do the event callback in its setter. This way, you won't forget to call the handlers.
Read more about events here.
This is enough to get you going. However, if you delve further into the C# framework, you will find a standardized way of using this event framework inside of the
System.ComponentModel
namespace. Sepcifically, the interfaceINotifyPropertyChanged
, which ties neatly into a more generic event system that also plays well with some of Microsoft's own technologies, such as WPF, allowing GUI elements to pick up on changes to your class automatically. Read more aboutINotifyPropertyChanged
here.您基本上需要 PropertyChangedEvent PropertyChangedEventHandler Delegate
You basically need PropertyChangedEvent PropertyChangedEventHandler Delegate
我认为 C# 属性 就是你的需要。
I think C# properties is what you need.