[英]Trigger an event when something changes in a class
当给定类中的某些内容发生变化时,是否可能触发某些事件?
例如,我有一个包含100
字段的类,其中一个字段在外部或内部进行修改。 现在我想抓住这个事件。 这个怎么做?
我最想知道是否有一个技巧可以快速完成扩展课程。
作为最佳实践,将公共字段转换为手动属性,并使用INotifyPropertyChanged
interface
实现您的class
,以便引发更改event
。
编辑:因为你提到了100个字段,我建议你重构你的代码,就像这个伟大的答案: 将C#公共字段重构为属性的工具
这是一个例子:
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));
}
}
看看这个: INotifyPropertyChanged接口
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.