[英]Trigger an event when something changes in a class
Is it possible to trigger some event when something changes in a given class? 当给定类中的某些内容发生变化时,是否可能触发某些事件?
Eg I have a class that has 100
fields and one of them is being modified externally or internally. 例如,我有一个包含100
字段的类,其中一个字段在外部或内部进行修改。 Now I want to catch this event. 现在我想抓住这个事件。 How to do this? 这个怎么做?
The most I wonder if there is a trick to do this quickly for really extended classes. 我最想知道是否有一个技巧可以快速完成扩展课程。
As a best practice, convert your public fields to manual properties and implement your class
with the INotifyPropertyChanged
interface
in order to raise a change event
. 作为最佳实践,将公共字段转换为手动属性,并使用INotifyPropertyChanged
interface
实现您的class
,以便引发更改event
。
EDIT: Because you mentioned 100 fields I would suggest you to refactor your code like in this great answer: Tools for refactoring C# public fields into properties 编辑:因为你提到了100个字段,我建议你重构你的代码,就像这个伟大的答案: 将C#公共字段重构为属性的工具
Here is an example of it: 这是一个例子:
private string _customerNameValue = String.Empty;
public string CustomerName
{
get
{
return this._customerNameValue;
}
set
{
if (value != this._customerNameValue)
{
this._customerNameValue = value;
NotifyPropertyChanged();
}
}
}
private void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
Check this out: INotifyPropertyChanged Interface 看看这个: INotifyPropertyChanged接口
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.