【问题标题】:Trigger an event when something changes in a class当类中的某些内容发生变化时触发事件
【发布时间】:2013-04-15 14:21:36
【问题描述】:

当给定类发生变化时是否可以触发某些事件?

例如我有一个具有100 字段的类,其中一个正在外部或内部进行修改。现在我想赶上这个事件。如何做到这一点?

我最想知道是否有一个技巧可以为真正的扩展类快速完成此操作。

【问题讨论】:

  • 这是为了调试,还是为了更新 UI?答案会有所不同。
  • 用于更新 UI 和做许多其他事情

标签: c# events


【解决方案1】:

作为最佳实践,将您的公共字段转换为手动属性并使用 INotifyPropertyChanged interface 实现您的 class 以引发更改 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));
    }
}

看看这个:INotifyPropertyChanged Interface

【讨论】:

猜你喜欢
  • 2014-02-22
  • 1970-01-01
  • 2018-03-30
  • 1970-01-01
  • 1970-01-01
  • 2012-03-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多