gpt4 book ai didi

c#-6.0 - 如何在符合 CLS 的程序集中使用 CallerMemberName

转载 作者:行者123 更新时间:2023-12-02 03:01:41 26 4
gpt4 key购买 nike

我在类的 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 方法?

最佳答案

我简单地删除了 CallerMemberName 属性和默认参数值,这意味着该参数不再是可选的,因此方法签名变为:

private void NotifyPropertyChanged(String propertyName)

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

NotifyPropertyChanged(nameof(FooProperty));

这似乎工作得很好。

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

关于c#-6.0 - 如何在符合 CLS 的程序集中使用 CallerMemberName,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45502525/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com