C# 中变量名前的 @ 符号是什么意思?
我知道可以在字符串文字之前使用 @ 符号来更改编译器解析字符串的方式。 但是当变量名以 @ 符号为前缀时,它意味着什么?
I understand that the @ symbol can be used before a string literal to change how the compiler parses the string. But what does it mean when a variable name is prefixed with the @ symbol?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
@ 符号允许您使用保留字。 例如:
上面的方法有效,而下面的方法则无效:
The @ symbol allows you to use reserved word. For example:
The above works, when the below wouldn't:
@ 符号在 C# 中有两个用途:
首先,它允许您使用保留关键字作为变量,如下所示:
第二个选项允许您指定字符串而无需转义任何字符。 例如,“\”字符是转义字符,因此通常您需要这样做:
或者您可以这样做:
The @ symbol serves 2 purposes in C#:
Firstly, it allows you to use a reserved keyword as a variable like this:
The second option lets you specify a string without having to escape any characters. For instance the '\' character is an escape character so typically you would need to do this:
alternatively you can do this:
其他答案忘记的重要一点是“@keyword”在 CIL 中被编译为“keyword”。
因此,如果您有一个用 F# 编写的框架,它要求您定义一个具有名为“class”的属性的类,那么您实际上可以做到这一点。
它在实践中没有什么用处,但没有它会阻止 C# 进行某些形式的语言互操作。
我通常看到它不是用于互操作,而是为了避免关键字限制(通常在局部变量名称上,这是唯一效果),即。
但我强烈反对这样做! 只需找到另一个名称,即使变量的“最佳”名称是保留名称之一。
An important point that the other answers forgot, is that "@keyword" is compiled into "keyword" in the CIL.
So if you have a framework that was made in, say, F#, which requires you to define a class with a property named "class", you can actually do it.
It is not that useful in practice, but not having it would prevent C# from some forms of language interop.
I usually see it used not for interop, but to avoid the keyword restrictions (usually on local variable names, where this is the only effect) ie.
but I would strongly discourage that! Just find another name, even if the 'best' name for the variable is one of the reserved names.
它允许您使用 C# 关键字作为变量。 例如:
It allows you to use a C# keyword as a variable. For example: