我应该提供一个带有nameof的成员名称的方法,还是应该依赖CallerMemberName来为我做这个?

时间:2016-06-21 11:07:35

标签: c# reflection nameof callermembername

CallerMemberName如何实施?

我得到了它的功能 - 它允许我们将魔术字符串保留在我们的代码之外 - 但是它应该在nameof上使用还有什么更高效的?

差异是什么/ CallerMemberName如何正常工作?

2 个答案:

答案 0 :(得分:4)

CallerMemberName是一个编译时技巧,用于将当前成员的名称放在对另一个方法的调用中。 nameof也是一个类似的编译时技巧:它采用成员的字符串表示。

使用哪个取决于您。我会说:尽可能使用CallerMemberNamenameof尽可能使用CallerMemberNamenameofvar dues = [{ memberid: 194, payment: [ { month: 'January', amount: 2500, year: 2015 }, { month: 'February', amount: 2500, year: 2015 }, { month: 'March', amount: 2500, year: 2015 }, { month: 'April', amount: 2500, year: 2015 }, { month: 'May', amount: 2500, year: 2015 }, { month: 'June', amount: 2500, year: 2015 }, { month: 'July', amount: 2500, year: 2015 }, { month: 'August', amount: 2500, year: 2015 }, { month: 'September', amount: 2500, year: 2015 }, { month: 'October', amount: 2500, year: 2015 }, { month: 'November', amount: 2500, year: 2015 }, { month: 'December', amount: 2500, year: 2015 }, { month: 'March', amount: 2500, year: 2016 }, { month: 'May', amount: 2500, year: 2016 }, { month: 'September', amount: 2500, year: 2016 } ], name: 'Makey Trashey' }, { memberid: 156, payment: [ { month: 'January', amount: 2500, year: 2015 }, { month: 'February', amount: 2500, year: 2015 }, { month: 'March', amount: 2500, year: 2015 }, { month: 'April', amount: 2500, year: 2015 }, { month: 'May', amount: 2500, year: 2015 }, { month: 'June', amount: 2500, year: 2015 }, { month: 'July', amount: 2500, year: 2015 }, { month: 'August', amount: 2500, year: 2015 }, { month: 'September', amount: 2500, year: 2015 }, { month: 'October', amount: 2500, year: 2015 }, { month: 'November', amount: 2500, year: 2015 }, { month: 'December', amount: 2500, year: 2015 }, { month: 'March', amount: 2500, year: 2016 }, { month: 'May', amount: 2500, year: 2016 }, { month: 'July', amount: 2500, year: 2016 } ], name: 'Makey Johnny' } ] 更加自动化,所以我更喜欢那个。

两者都具有相同的性能含义:仅在编译时需要一些额外的时间来评估代码,但这是可以忽略的。

答案 1 :(得分:4)

[CallerMemberName]nameof不完全可互换。有时你需要第一个,有时候 - 第二个,即使我们正在谈论相同的方法:

class Foo : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    protected virtual void OnPropertyChanged([CallerMemberName]string propertyName = null)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }

    private string title;

    public string Title
    {
        get { return title; }
        set
        {
            if (title != value)
            {
                title = value;
                // we're using CallerMemberName here
                OnPropertyChanged();
            }
        }
    }

    public void Add(decimal value)
    {
        Amount += value;
        // we can't use CallerMemberName here, because it will be "Add";
        // instead of this we have to use "nameof" to tell, what property was changed
        OnPropertyChanged(nameof(Amount));
    }

    public decimal Amount { get; private set; }
}