【问题标题】:How to use CallerMemberName in a CLS compliant assembly如何在符合 CLS 的程序集中使用 CallerMemberName
【发布时间】:2017-08-04 09:01:57
【问题描述】:

我在INotifyPropertyChanged 的类实现中使用了CallerMemberName 属性,如MSDN 所述,如下所示:

    public event PropertyChangedEventHandler PropertyChanged;

    // This method is called by the Set accessor of each property.
    // The CallerMemberName attribute that is applied to the optional propertyName
    // parameter causes the property name of the caller to be substituted as an argument.
    private void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }

但是,使用默认参数不符合 CLS。但是CallerMemberName只能和有默认值的参数一起使用……有没有一种常用的方法来解决这种不一致,而不必用硬编码的字符串参数调用notify方法?

【问题讨论】:

    标签: c#-6.0 default-parameters cls-compliant


    【解决方案1】:

    我只是简单地去掉了CallerMemberName属性和默认参数值,意味着参数不再是可选的,所以方法签名变成了:

    private void NotifyPropertyChanged(String propertyName)
    

    然后使用提供字符串参数的nameof 运算符调用它是一个很小(足够)的更改:

    NotifyPropertyChanged(nameof(FooProperty));
    

    这似乎工作得很好。

    我会暂时搁置这个问题,因为其他人可能有更好的方法,或者提出这个解决方案的问题。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-01
      • 1970-01-01
      • 2018-04-02
      • 1970-01-01
      相关资源
      最近更新 更多