nameof的目的是什么?目的、nameof

2023-09-03 11:50:01 作者:單刀赴会

6.0版本使用了 nameof 的一项​​新功能,但我不明白它的目的,因为它只是需要变量名,并将其改变为一个字符串编辑。

Version 6.0 got a new feature of nameof, but I can't understand the purpose of it, as it just takes the variable name and changes it to a string on compilation.

我想这可能使用时有一定的目的< T> 但是当我尝试 nameof(T)这只是打印了我一个 T 所使用的类型,而不是。

I thought it might have some purpose when using <T> but when I try to nameof(T) it just prints me a T instead of the used type.

在目的任何想法?

推荐答案

那么,你希望根据属性名抛出异常时,或处理一个的PropertyChanged 事件。有许多情况下,您都需要有属性的名称。

What about cases where you want to reuse the name of a property, for example when throwing exception based on a property name, or handling a PropertyChanged event. There are numerous cases where you would want to have the name of the property.

拿这个例子:

switch (e.PropertyName)
{
    case nameof(SomeProperty):
    { break };

    // opposed to
    case "SomeOtherProperty":
    { break;}
}

在第一种情况下,重命名 SomeProperty 将改变属性的名称太多,否则会破坏编辑。最后一种情况并非如此。

In the first case, renaming SomeProperty will change the name of the property too, or it will break compilation. The last case doesn't.

这是保持你的code编译和无bug(排序的)。

This is a very useful way to keep your code compiling and bug free (sort-of).

(A 非常好的文章从埃里克利珀的原因 infoof 没能成功,而 nameof 一样)

(A very nice article from Eric Lippert why infoof didn't make it, while nameof did)

 
精彩推荐