美文网首页
INotifyPropertyChanged 接口的优雅用法:F

INotifyPropertyChanged 接口的优雅用法:F

作者: 电工王大爷 | 来源:发表于2020-10-16 16:45 被阅读0次

    通过Nuget安装库,使用如下命令:

    PM> Install-Package PropertyChanged.Fody
    

    然后在需要实现属性通知的上添加一个[AddINotifyPropertyChangedInterface]即可,如下所示:

      [AddINotifyPropertyChangedInterface]
      public class Person
      {
    
        public string GivenNames { get; set; }
        public string FamilyName { get; set; }
    
        public string FullName => string.Format("{0} {1}", GivenNames, FamilyName);
      }
    

    编译后等效代码如下:

    public class Person : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;
    
        string givenNames;
        public string GivenNames
        {
            get { return givenNames; }
            set
            {
                if (value != givenNames)
                {
                    givenNames = value;
                    OnPropertyChanged("GivenNames");
                    OnPropertyChanged("FullName");
                }
            }
        }
    
        string familyName;
        public string FamilyName
        {
            get { return familyName; }
            set 
            {
                if (value != familyName)
                {
                    familyName = value;
                    OnPropertyChanged("FamilyName");
                    OnPropertyChanged("FullName");
                }
            }
        }
    
        public string FullName
        {
            get
            {
                return string.Format("{0} {1}", GivenNames, FamilyName);
            }
        }
    
        public virtual void OnPropertyChanged(string propertyName)
        {
            var propertyChanged = PropertyChanged;
            if (propertyChanged != null)
            {
                propertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }
    }
    

    基本上对代码没有注入,不需要安装插件,也不影响调试,实现非常简单,非常方便。
    需要注意的是,如果实现了INotifyPropertyChanged接口,即使没有[ImplementPropertyChanged]标记,默认也会注入。

    相关文章

      网友评论

          本文标题:INotifyPropertyChanged 接口的优雅用法:F

          本文链接:https://www.haomeiwen.com/subject/azoapktx.html