C#中变量名前的@符号是什么意思?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/429529/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 03:01:59  来源:igfitidea点击:

What does the @ symbol before a variable name mean in C#?

c#variablesnamingspecificationsreserved-words

提问by Greg

Possible Duplicate:
What's the use/meaning of the @ character in variable names in C#?

可能的重复:
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?

我知道可以在字符串文字之前使用 @ 符号来更改编译器解析字符串的方式。但是当变量名以@ 符号为前缀时,这意味着什么?

采纳答案by Michael Meadows

The @ symbol allows you to use reserved word. For example:

@ 符号允许您使用保留字。例如:

int @class = 15;

The above works, when the below wouldn't:

以上工作,当以下不会:

int class = 15;

回答by Joel Coehoorn

It allows you to use a C# keyword as a variable. For example:

它允许您使用 C# 关键字作为变量。例如:

class MyClass
{
   public string name { get; set; }
   public string @class { get; set; }
}

回答by Micah

The @ symbol serves 2 purposes in C#:

@ 符号在 C# 中有两个用途:

Firstly, it allows you to use a reserved keyword as a variable like this:

首先,它允许您使用保留关键字作为变量,如下所示:

int @int = 15;

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:

第二个选项允许您指定一个字符串而不必转义任何字符。例如 '\' 字符是一个转义字符,所以通常你需要这样做:

var myString = "c:\myfolder\myfile.txt"

alternatively you can do this:

或者你可以这样做:

var myString = @"c:\myFolder\myfile.txt"

回答by Rasmus Faber

An important point that the other answers forgot, is that "@keyword" is compiled into "keyword" in the CIL.

其他答案忘记的重要一点是,“@keyword”在 CIL 中被编译为“keyword”。

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.

因此,如果您有一个框架,例如,F#,它要求您定义一个具有名为“class”的属性的类,那么您实际上可以做到。

It is not thatuseful in practice, but not having it would prevent C# from some forms of language interop.

这并不是有用的做法,但没有它会阻止C#从某些形式的语言互操作的。

I usually see it used not for interop, but to avoid the keyword restrictions (usually on local variable names, where this is the onlyeffect) ie.

我通常看到它不是用于互操作,而是为了避免关键字限制(通常在局部变量名称上,这是唯一的效果)即。

private void Foo(){
   int @this = 2;
}

but I would strongly discourage that! Just find another name, even if the 'best' name for the variable is one of the reserved names.

但我强烈反对!只需找到另一个名称,即使变量的“最佳”名称是保留名称之一。