1

我想在属性更改时收到通知,以便我可以在数据库中记录属性的旧值和新值。

所以我决定采用属性设置器的方法,并有一个处理所有属性的通用方法。

我创建了下面的类:

public class PropertyChangedExtendedEventArgs<T> : PropertyChangedEventArgs
{
    public virtual T OldValue { get; private set; }
    public virtual T NewValue { get; private set; }

    public PropertyChangedExtendedEventArgs(string propertyName,
                                            T oldValue, T newValue)
        : base(propertyName)
    {
        OldValue = oldValue;
        NewValue = newValue;

   //write to database the values!!!
    }
}

在我的财产上,我这样称呼它:

private string _surname;
public string Surname
{
    get { return _surname; }
    set 
    {
        string temp = Surname;
        _surname = value;
        Helper.PropertyChangedExtendedEventArgs("Surname", temp, value);
    }
}

但这是第一次使用泛型,所以很少有顾虑:

  • 我如何在我的财产上调用它?
  • 这是一个好方法吗?
  • 我可以公开调用函数 PropertyChangedExtendedEventArgs(string propertyName, T oldValue, T newValue)并保存到数据库吗?
4

1 回答 1

3

您似乎对属性更改的使用有些困惑。
通常,希望对其属性进行观察的组件会更改INotifyPropertyChanged接口。因此,正确的实现将类似于

private string _surname;
public string Surname
{
    get { return _surname; }
    set 
    {
        if (_surname != value) // IMP: you want to inform only if value changes
        {
           string temp = Surname;
           _surname = value;

           // raise property change event, 
           NotifyPropertyChanged(temp, _surname);
        }
    }
}

Typically, base implementation could provide helper implementation to raise the event - for example,

public abstract Component : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    protected void NotifyPropertyChanged<T>(T oldVal, T newVal, [CallerMemberName] String propertyName = "")
    {
       var e = PropertyChanged;
       if (e != null)
       {
          e(this, new PropertyChangedExtendedEventArgs(propertyName, oldVal, newVal));
       }
    }
}

Now, its consumer's responsibility on how to react to property changes. This separates observable components from unrelated concern of what to do when some property changes. Typically, one will have some the common implementation that would say - save the current object state in stacked manner as to provide undo-redo functionality.

因此,在您的情况下,您希望将它们记录到数据库(?),应该有代码可以侦听此属性更改事件并进行记录。将有一些控制器/绑定代码将遍历所有实现此接口的对象并连接事件。通常,根级容器会进行此类内部管理——例如,在设计器界面中,每当创建新组件并将其添加到设计界面时,其根元素(或处理根元素的代码)都会连接事件。

于 2013-01-22T10:20:08.500 回答