问题
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