为什么我不能从一个扩展方法调用PropertyChanged事件? [英] Why can't I invoke PropertyChanged event from an Extension Method?

查看:229
本文介绍了为什么我不能从一个扩展方法调用PropertyChanged事件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图代码的类,以避免像RaisePropertyChanged的方法。我知道我可以从有实施类继承,但在某些情况下,我不能。我已经试过了扩展方法,但Visual Studio的抱怨。

 公共静态类扩展
{
公共静态无效RaisePropertyChanged(这INotifyPropertyChanged的谓词,字符串propertyName的)
{
如果(predicate.PropertyChanged!= NULL)
{
predicate.PropertyChanged(propertyName的,新的PropertyChangedEventArgs(propertyName的) );
}
}
}



它说:




事件
'的 System.ComponentModel.INotifyPropertyChanged.PropertyChanged'可以
只出现在左侧的+ =或 - =



解决方案

里德是正确的。不过,我看你想要做什么(使你的代码reusable- 对你有好处);而我只想指出,这往往容易被接受 PropertyChangedEventHandler 代表的本身,并从 INotifyPropertyChanged的实施

 公共静态无效抬起(这PropertyChangedEventHandler处理程序,对象发件人,字符串propertyName的) 
{
如果
{
处理器(发件人,新PropertyChangedEventArgs(propertyName的))(处理!= NULL);
}
}

这是您的类,它实现<$ C $内再C> INotifyPropertyChanged的,你可以调用像这样这个扩展的方法:

  PropertyChanged.Raise(这一点, myProperty的); 

这工作,因为,的为马克说,类中声明你的事件可以的访问它像场(这意味着你可以把它作为一个委托参数的方法,包括扩展方法)。


I've tried to code a class to avoid a method like "RaisePropertyChanged". I know that I can inherit from a class that has that implementation but in some cases I can't. I've tried with a Extension Method but Visual Studio complain.

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

It said:

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

解决方案

Reed is right. However, I see what you're trying to do (make your code reusable—good for you); and I'll just point out that this is often easily rectified by accepting the PropertyChangedEventHandler delegate itself and passing it from within the INotifyPropertyChanged implementation:

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

Then from within your class which implements INotifyPropertyChanged, you can call this extension method like so:

PropertyChanged.Raise(this, "MyProperty");

This works because, as Marc said, within the class declaring the event you can access it like a field (which means you can pass it as a delegate argument to a method, including extension methods).

这篇关于为什么我不能从一个扩展方法调用PropertyChanged事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆