Why doesn't the compiler give any errors or warnings when using this hack?

烂漫一生 提交于 2019-12-24 18:29:21

问题


In my other question, I found a hack to make this syntax work in MonoDevelop editor:

// hack to make MonoDevelop recognize nameof syntax from C#6.0
using nameof = System.Func<string>;

The C# compilers (Mono and VS) don't give any warnings or errors, and usages of the nameof keyword also work normally. My question is why.


回答1:


I'm not a language lawyer but I believe the reason your code works is that nameof is a contextual keyword

Let's take a step back to a more general case. If you try to create a using alias directive for the keyword if you get an error...

using if = System.Func<string>;  // "CS1001: Identifier expected" error

… unless you prefix the name with @ ...

using @if = System.Func<string>;  // No "CS1001: Identifier expected" error

Similarly you get a CS1003 error if you try to declare a variable of the aliased type ...

if foo = () => "Hello, World";  // "CS1003: Syntax error, '(' expected" error

… unless you prefix the name with an @ sign …

@if foo = () => "Hello, World";  // No "CS1003: Syntax error, '(' expected" error

Contextual keywords on the other hand do not need to be prefixed by @

using nameof = System.Func<string>;

nameof bar = () => "Hello, World!";

Console.WriteLine(nameof(nameof));


来源:https://stackoverflow.com/questions/51457554/why-doesnt-the-compiler-give-any-errors-or-warnings-when-using-this-hack

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!