相关疑难解决方法(0)

调用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);
        }
   }
Run Code Online (Sandbox Code Playgroud)

这是每个属性12行.

如果一个人能够装饰这样的自动属性会简单得多:

[INotifyProperty]
public double MyField{ get; set; }
Run Code Online (Sandbox Code Playgroud)

但不幸的是,这是不可能的(例如,请参阅msdn上的这篇文章)

如何减少每个属性所需的代码量?

.net c# automatic-properties inotifypropertychanged .net-3.5

10
推荐指数
2
解决办法
8193
查看次数