为什么我不能这样写扩展方法?在课堂上我可以使用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'只能出现在+ =或 - =
的左侧答案 0 :(得分:0)
这是C#语言的规范。无法将事件属性分配给某些处理程序。事件字段是可能的。
如果您对OnPropertyChanged方法没有任何特殊限制(调试,日志记录..),我建议在standart类而不是扩展名中进行定义。
您只能使用此:
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));
}
}