6.0版获得了nameof的新功能,但我不能理解它的目的,因为它只是接受变量名并在编译时将其更改为字符串。
我认为它在使用<T>时可能有一些目的,但当我尝试命名(T)时,它只是打印我一个T而不是使用的类型。
知道目的吗?
6.0版获得了nameof的新功能,但我不能理解它的目的,因为它只是接受变量名并在编译时将其更改为字符串。
我认为它在使用<T>时可能有一些目的,但当我尝试命名(T)时,它只是打印我一个T而不是使用的类型。
知道目的吗?
当前回答
我能想到的最常见的用例是使用INotifyPropertyChanged接口时。(基本上所有与WPF和绑定相关的东西都使用这个接口)
看看这个例子:
public class Model : INotifyPropertyChanged
{
// From the INotifyPropertyChanged interface
public event PropertyChangedEventHandler PropertyChanged;
private string foo;
public String Foo
{
get { return this.foo; }
set
{
this.foo = value;
// Old code:
PropertyChanged(this, new PropertyChangedEventArgs("Foo"));
// New Code:
PropertyChanged(this, new PropertyChangedEventArgs(nameof(Foo)));
}
}
}
正如您可以看到的,在旧的方法中,我们必须传递一个字符串来指示哪个属性已经更改。使用nameof,我们可以直接使用属性的名称。这可能看起来没什么大不了的。但是想象一下如果有人改变了属性Foo的名字会发生什么。当使用字符串时,绑定将停止工作,但编译器不会警告你。当使用nameof时,你会得到一个编译器错误,没有名称Foo的属性/参数。
请注意,有些框架使用一些反射魔法来获取属性的名称,但现在我们不再需要nameof this了。
其他回答
它在使用ASP时具有一定的优势。净MVC。当你使用HTML helper在视图中构建一些控件时,它使用HTML输入的name属性中的属性名:
@Html.TextBoxFor(m => m.CanBeRenamed)
它是这样的:
<input type="text" name="CanBeRenamed" />
所以现在,如果你需要在validate方法中验证你的属性,你可以这样做:
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext) {
if (IsNotValid(CanBeRenamed)) {
yield return new ValidationResult(
$"Property {nameof(CanBeRenamed)} is not valid",
new [] { $"{nameof(CanBeRenamed)}" })
}
}
如果你使用重构工具重命名你的属性,你的验证不会被破坏。
它对ArgumentException及其衍生物非常有用:
public string DoSomething(string input)
{
if(input == null)
{
throw new ArgumentNullException(nameof(input));
}
...
现在,如果有人重构输入参数的名称,异常也将保持最新。
在以前必须使用反射来获取属性或参数名称的某些地方,它也很有用。
在你的例子中,nameof(T)获取类型参数的名称-这也很有用:
throw new ArgumentException(nameof(T), $"Type {typeof(T)} does not support this method.");
nameof的另一种用法是用于枚举——通常如果你想要枚举的字符串名称,你可以使用.ToString():
enum MyEnum { ... FooBar = 7 ... }
Console.WriteLine(MyEnum.FooBar.ToString());
> "FooBar"
这实际上相对较慢,因为. net保存枚举值(即7)并在运行时查找名称。
用nameof代替:
Console.WriteLine(nameof(MyEnum.FooBar))
> "FooBar"
现在。net在编译时将枚举名称替换为字符串。
还有一种用法是INotifyPropertyChanged和日志记录——在这两种情况下,你都想把你调用的成员的名字传递给另一个方法:
// Property with notify of change
public int Foo
{
get { return this.foo; }
set
{
this.foo = value;
PropertyChanged(this, new PropertyChangedEventArgs(nameof(this.Foo));
}
}
还是……
// Write a log, audit or trace for the method called
void DoSomething(... params ...)
{
Log(nameof(DoSomething), "Message....");
}
nameof关键字的用法之一是在wpf中以编程方式设置Binding。
要设置绑定,你必须设置路径字符串和nameof关键字,可以使用重构选项。
例如,如果你在你的UserControl中有IsEnable依赖属性,你想把它绑定到你的UserControl中某些复选框的IsEnable上,你可以使用这两个代码:
CheckBox chk = new CheckBox();
Binding bnd = new Binding ("IsEnable") { Source = this };
chk.SetBinding(IsEnabledProperty, bnd);
and
CheckBox chk = new CheckBox();
Binding bnd = new Binding (nameof (IsEnable)) { Source = this };
chk.SetBinding(IsEnabledProperty, bnd);
很明显,第一个代码不能重构,但第二个代码……
之前我们使用的是这样的东西:
// Some form.
SetFieldReadOnly( () => Entity.UserName );
...
// Base form.
private void SetFieldReadOnly(Expression<Func<object>> property)
{
var propName = GetPropNameFromExpr(property);
SetFieldsReadOnly(propName);
}
private void SetFieldReadOnly(string propertyName)
{
...
}
原因-编译时安全。没有人可以默默地重命名属性并破坏代码逻辑。现在我们可以使用nameof()。
你的问题已经表达了目的。您必须看到,这对于记录日志或抛出异常可能很有用。
例如:
public void DoStuff(object input)
{
if (input == null)
{
throw new ArgumentNullException(nameof(input));
}
}
这很好。如果我更改了变量的名称,代码将中断,而不是返回带有错误消息的异常。
当然,用途并不局限于这种简单的情况。只要对变量或属性的名称进行编码是有用的,就可以使用nameof。
当您考虑各种绑定和反射情况时,其用途是多方面的。这是一种将运行时错误带到编译时的极好方法。