有没有办法将规范的 OnPropertyChanged 方法编写为扩展方法?
基本上我想做这样的事情:
public static void OnPropertyChanged(this INotifyPropertyChanged changedObject, string propertyName)
{
var handler = changedObject.PropertyChanged;
if (handler != null)
{
var e = new PropertyChangedEventArgs(propertyName);
handler(changedObject, e);
}
}
这给出了“System.ComponentModel.INotifyPropertyChanged.PropertyChanged只能在+=或-=”的左侧使用
我的意思是我可以通过这样做来解决它:
public static void RaisePropertyChanged(this PropertyChangedEventHandler handler, object sender, string propertyName)
{
if (handler != null)
{
var e = new PropertyChangedEventArgs(propertyName);
handler(sender, e);
}
}
但是调用代码看起来不太好:
PropertyChanged.RaisePropertyChanged(this, "Name");
vs this:
this.OnPropertyChanged("Name");
没什么大不了的,但如果能够像调用实例方法一样调用它就好了。
basically I want to do something like this:
public static void OnPropertyChanged(this INotifyPropertyChanged changedObject, string propertyName)
{
var handler = changedObject.PropertyChanged;
if (handler != null)
{
var e = new PropertyChangedEventArgs(propertyName);
handler(changedObject, e);
}
}
which gives "System.ComponentModel.INotifyPropertyChanged.PropertyChanged can only be used on the left-hand side of += or -="
I mean I can work around it by doing this:
public static void RaisePropertyChanged(this PropertyChangedEventHandler handler, object sender, string propertyName)
{
if (handler != null)
{
var e = new PropertyChangedEventArgs(propertyName);
handler(sender, e);
}
}
but the calling code doesn't look quite as nice:
PropertyChanged.RaisePropertyChanged(this, "Name");
vs this:
this.OnPropertyChanged("Name");
Not a big deal, but it'd be nice to be able to call it as if it was an instance method.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这也违反了准则:On* 方法通常意味着基于实现实例内部的某些内容来执行操作。 一般来说,这些方法是虚拟的,因此您可以在派生类中重写它们。 因此,在外部使用 On* 方法是没有意义的。 如果您想引发一个事件,而又不想到处进行可怕的空测试,那么您确实应该使用 RaiseEvent() 扩展方法。 我写了很多这些,所有这些都具有重载,因此您可以只使用 RaiseEvent(...) 并且不必在方法中包含事件的名称。 例如,当您使用普通的 EventHandler 类型时,这尤其容易,因此您可以对更多事件使用相同的扩展方法。
It's also against the guidelines: On* methods in general are meant to do things based on something which INSIDE the implementing instance. In general these methods are virtual so you can override them in derived classes. Having an On* method externally therefore makes no sense. If you want to raise an event without having the dreaded null-test all over the place you indeed should use a RaiseEvent() extension method. I wrote a lot of these, all having overloads so you can just have RaiseEvent(... ) and you don't have to include the name of the event in the method. This is particularly easy in cases where you for example use the normal EventHandler type, so you can use the same extension method for more events.