c# - 为什么我不能从扩展方法调用 PropertyChanged 事件?

标签 c# wpf extension-methods inotifypropertychanged propertychanged

我尝试编写一个类来避免使用像“RaisePropertyChanged”这样的方法。我知道我可以从具有该实现的类继承,但在某些情况下我不能。我试过使用扩展方法,但 Visual Studio 提示。

public static class Extension
{
    public static void RaisePropertyChanged(this INotifyPropertyChanged predicate, string propertyName)
    {
        if (predicate.PropertyChanged != null)
        {
            predicate.PropertyChanged(propertyName, new PropertyChangedEventArgs(propertyName));
        }
    }
}

它说:

"The event 'System.ComponentModel.INotifyPropertyChanged.PropertyChanged' can only appear on the left hand side of += or -="

最佳答案

Reed是对的。但是,我明白你在做什么(让你的代码可重用——对你有好处);我只想指出,通过接受 PropertyChangedEventHandler delegate 本身并从 INotifyPropertyChanged 实现中传递它,通常可以很容易地纠正这个问题:

public static void Raise(this PropertyChangedEventHandler handler, object sender, string propertyName)
{
    if (handler != null)
    {
        handler(sender, new PropertyChangedEventArgs(propertyName));
    }
}

然后在实现了 INotifyPropertyChanged 的类中,您可以像这样调用这个扩展方法:

PropertyChanged.Raise(this, "MyProperty");

之所以有效,是因为 as Marc said ,在声明事件的类中,您可以像访问字段一样访问它(这意味着您可以将它作为委托(delegate)参数传递给方法,包括扩展方法)。

关于c# - 为什么我不能从扩展方法调用 PropertyChanged 事件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4925106/

相关文章:

c# - 从代码填充 UWP 组合框

c# - 如何使用带有 Xamarin 的 MVVM 在 XAML 中动态更改图像源

c# - 动态文字控件内的动态按钮

wpf - 为什么将 DependencyProperty 成员声明为 public 不 protected ?

wpf - 在 WPF 中的另一个数据模板中使用一个数据模板

c# - 将 C# 链接起来看起来像 jQuery 是一个好主意吗?

swift - 为什么 Swift 的运行时不能将存储的属性放入现有的结构中进行扩展?

c# - 重铸为派生类型

wpf - WPF SplashScreen实现

c# - 为什么 LINQ to SQL 不支持查询运算符 'ElementAt'?