为什么我不能从一个扩展方法调用PropertyChanged事件?

编程入门 行业动态 更新时间:2024-10-20 18:57:39
本文介绍了为什么我不能从一个扩展方法调用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); } }

这是您的类,它实现 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事件?

本文发布于:2023-10-31 06:10:17,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1545246.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:事件   方法   PropertyChanged

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!