在类中发生更改时触发事件

Nic*_*kon 7 c# events

当给定类中的某些内容发生变化时,是否可能触发某些事件?

例如,我有一个具有100字段的类,其中一个字段在外部或内部进行修改.现在我想抓住这个事件.这该怎么做?

我最想知道是否有一个技巧可以快速完成扩展课程.

Yai*_*vet 13

作为最佳实践,将您的公共领域的手动特性和实现classINotifyPropertyChanged interface以提高改变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));
    }
}
Run Code Online (Sandbox Code Playgroud)

看看这个:INotifyPropertyChanged接口

  • 歪曲你的代码!看看它是多么简单:[将C#公共字段重构为属性的工具](http://stackoverflow.com/questions/1028679/tools-for-refactoring-c-sharp-public-fields-into-properties) (2认同)