扩展中的CallerMemberName(INotifyPropertyChanged) [英] CallerMemberName in an extension (INotifyPropertyChanged)

查看:114
本文介绍了扩展中的CallerMemberName(INotifyPropertyChanged)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我当前正在为INotifiyPropertyChanged接口实现扩展,您可以阅读以下内容:

I am currently implementing an Extension for the INotifiyPropertyChanged interface, you can read this:

INotifyPropertyChanged-事件保持为空

以获取更多信息.

现在,我想进一步扩展此扩展名,这样我就无需声明MemberExpression,并且在从一个内部调用它时,CallerMemberName Attribute可以完成其余工作.

Now I would like to extend this extension further so that I dont need to state the MemberExpression and when calling it from inside a set that the CallerMemberName Attribute does the rest.

因此,我尝试执行以下操作(基于我上一个stackoverflow问题中提供的链接):

So I have tried to do the following (based on the links provided in my last stackoverflow question):

public static void Notify(this PropertyChangedEventHandler EventHandler, object sender, 
[CallerMemberName] String propertyName = "")
{
    if (EventHandler != null)
    {
        EventHandler(sender, new PropertyChangedEventArgs(propertyName));
    }
}

这允许我这样调用方法:

This allows me to call the method like this:

this.PropertyChanged.Notify(this); //with CallerMemberName
this.PropertyChanged.Notify(this, "RandomProperty"); 

现在,我想删除始终写(this ..)参数并像这样调用它的必要性:

Now I would like to remove the neccessarity to always write the (this, ..) parameter and just call it like so:

this.PropertyChanged.Notify(); //with CallerMemberName
this.PropertyChanged.Notify("RandomProperty"); 

这怎么可能?

推荐答案

简单来说,不可能.您需要3条信息:

Simply, it isn't possible. You need 3 pieces of information:

  • 事件处理程序实例(this.PropertyChanged,在左侧)
  • 事件名称(propertyName,由编译器提供)
  • 发件人(sender)
  • the event-handler instance (this.PropertyChanged, on the left)
  • the event-name (propertyName, supplied by the compiler)
  • the sender (sender)

sender不能从任何其他信息中推断出来,并且没有编译器选项可以提供.但是,坦率地说,我将只使用实例方法来代替:

sender cannot be inferred from any of the other information, and there is no compiler option to provide it. However, frankly, I would simply use an instance method instead:

protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
    var handler = PropertyChanged;
    if(handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
}

然后,呼叫者只需发出:

Then the caller simply issues:

OnPropertyChanged(); // job done

您当然可以OnPropertyChanged调用您的静态方法,但这似乎不必要.

You could of course have OnPropertyChanged call your static method, but that seems unnecessary.

以某种方式感觉,就像我们应该能够传入INotifyPropertyChanged实例以同时用于sender和访问PropertyChanged一样,但是当然我们可以不能从event声明中获取实际的委托.

In some ways it feels like we should be able to just pass in the INotifyPropertyChanged instance to use for both sender and to access the PropertyChanged, but of course we can't get the actual delegate from an event declaration.

这篇关于扩展中的CallerMemberName(INotifyPropertyChanged)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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