当给定类中的某些内容发生变化时,是否可以触发某些事件?
E.g。我有一个具有100
个字段的类,其中一个字段在外部或内部进行修改。现在我想抓住这个事件。怎么做?
我最想知道是否有一个技巧可以快速完成扩展课程。
答案 0 :(得分:13)
作为最佳做法,请将您的公开字段转换为手动媒体资源,并使用class
INotifyPropertyChanged
实施interface
,以便提出更改event
。
编辑:因为您提到了100个字段,我建议您重构代码,例如:Tools for refactoring C# public fields into properties
以下是一个例子:
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));
}
}