c# – 调用INotifyPropertyChanged的PropertyChanged事件的最佳方式是什么?

前端之家收集整理的这篇文章主要介绍了c# – 调用INotifyPropertyChanged的PropertyChanged事件的最佳方式是什么?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
当您实现INotifyPropertyChanged接口时,您负责在类中更新属性调用PropertyChanged事件.

这通常导致以下代码

public class MyClass: INotifyPropertyChanged

        private bool myfield;
        public bool MyField
        {
            get { return myfield; }
            set
            {
                if (myfield == value)
                    return;
                myfield = value;
                OnPropertyChanged(new PropertyChangedEventArgs("MyField"));
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;

        private void OnPropertyChanged(PropertyChangedEventArgs e)
        {
            PropertyChangedEventHandler h = PropertyChanged;
            if (h != null)
                h(this,e);
        }
   }

这是每个财产12行.

如果能够像这样装饰自动属性,将会更简单:

[INotifyProperty]
public double MyField{ get; set; }

但不幸的是这是不可能的(例如,见msdn上的this post)

如何减少每个物业所需的代码量?

解决方法

其实,每件物业只有3-4线;其他行通过所有“通知属性摊销:
class Person : INotifyPropertyChanged
{
    #region INotifyPropertyChanged: Shared bit
    public event PropertyChangedEventHandler PropertyChanged;

    private void OnPropertyChanged(PropertyChangedEventArgs e)
    {
        if (PropertyChanged != null)
            PropertyChanged(this,e);
    }
    #endregion

    private string _firstName;
    public string FirstName
    {
        get { return _firstName; }
        set
        {
            if (_firstName == value)
                return;
            _firstName = value;
            OnPropertyChanged(new PropertyChangedEventArgs("FirstName"));
        }
    }

    // Ditto for other properties
}

你可以尝试像下面这样的东西,它们分享一些更多的负载

private string _firstName;
public string FirstName
{
    get { return _firstName; }
    set { SetNotifyingProperty("FirstName",ref _firstName,value); }
}
private void SetNotifyingProperty<T>(string propertyName,ref T field,T value)
{
    if (value.Equals(field))
        return;
    field = value;
    OnPropertyChanged(new PropertyChangedEventArgs(propertyName));
}

猜你在找的C#相关文章