CallerMemberName如何实施?
我得到了它的功能 - 它允许我们将魔术字符串保留在我们的代码之外 - 但是它应该在nameof
上使用还有什么更高效的?
差异是什么/ CallerMemberName如何正常工作?
答案 0 :(得分:4)
CallerMemberName
是一个编译时技巧,用于将当前成员的名称放在对另一个方法的调用中。 nameof
也是一个类似的编译时技巧:它采用成员的字符串表示。
使用哪个取决于您。我会说:尽可能使用CallerMemberName
,nameof
尽可能使用CallerMemberName
。 nameof
比var 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; }
}