为什么在使用此hack时编译器没有给出任何错误或警告? [英] Why doesn't the compiler give any errors or warnings when using this hack?

查看:129
本文介绍了为什么在使用此hack时编译器没有给出任何错误或警告?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的其他问题中,我发现了一个使Mono语法在MonoDevelop编辑器中起作用的技巧:

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>;

C#编译器(Mono和VS)不发出任何警告或错误,并且nameof关键字的用法也可以正常工作.我的问题是为什么.

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.

推荐答案

我不是语言律师,但我相信您的代码有效的原因是nameof上下文关键字

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

让我们回到更一般的情况.如果您尝试创建 using alias directive 关键字if会出错...

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

类似地,如果您尝试声明别名类型的变量,则会收到CS1003错误.

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));

这篇关于为什么在使用此hack时编译器没有给出任何错误或警告?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆