【问题标题】:Extension method for INotifyPropertyChangedINotifyPropertyChanged 的​​扩展方法
【发布时间】:2016-03-05 10:48:45
【问题描述】:

为什么我不能写这样的扩展方法?在课堂上我可以使用 this.PropertyChanged != null。是编译器限制、dotnet 规范限制还是内部代码实现限制?我的开发人员直觉告诉我这应该是可能的;)。

public static class Ext {
        public static void OnPropertyChanged(this INotifyPropertyChanged npc, string propertyName) {
            if (npc.PropertyChanged != null) {
                npc.PropertyChanged(npc, new PropertyChangedEventArgs(propertyName));
            }
        }
    }

错误事件“System.ComponentModel.INotifyPropertyChanged.PropertyChanged”只能出现在+=或-=的左侧

【问题讨论】:

    标签: extension-methods inotifypropertychanged


    【解决方案1】:

    这是c#语言的规范。事件属性不可能分配给某些处理程序。事件字段是可能的。

    如果您对 OnPropertyChanged 方法(调试、日志记录..)没有任何特殊限制,我建议在标准类中定义它,而不是在扩展中。

    你只能使用这个:

    public class MyClass : INotifyPropertyChanged
    {
    
        public event PropertyChangedEventHandler PropertyChanged; // THIS IS FIELD, NOT PROPERTY, BUT YOU MAY DEFINE FROM INTERFACE
        protected void OnPropertyChanged([CallerMemberName] string propertyName = "")
        {
            this.OnPropertyChanged(PropertyChanged,propertyName );
        }
    
        private string name;
        public string Name
        {
            get => name;
            set { name = Name; this.OnPropertyChanged(); }
        }
    }
    
    public static class INotifyPropertyChangedExtension {
    
        public static void OnPropertyChanged(this INotifyPropertyChanged notifyPropertyChanged, PropertyChangedEventHandler propertyChanged, [CallerMemberName] string propertyName = "")
        {
            propertyChanged?.Invoke(notifyPropertyChanged, new PropertyChangedEventArgs(propertyName));
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-02-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-03-12
      相关资源
      最近更新 更多