这是c#(或可能是VB.net)的.NET问题,但我试图弄清楚以下声明之间的区别:
string hello = "hello";
vs.
string hello_alias = @"hello";
在控制台上打印没有区别,长度属性是相同的。
这是c#(或可能是VB.net)的.NET问题,但我试图弄清楚以下声明之间的区别:
string hello = "hello";
vs.
string hello_alias = @"hello";
在控制台上打印没有区别,长度属性是相同的。
当前回答
http://msdn.microsoft.com/en-us/library/aa691090.aspx
c#支持两种形式的字符串字面量:常规字符串字面量和逐字字符串字面量。
常规字符串文字由0个或多个用双引号括起来的字符组成,如"hello",并且可能包括简单转义序列(如制表符的\t)和十六进制和Unicode转义序列。
A verbatim string literal consists of an @ character followed by a double-quote character, zero or more characters, and a closing double-quote character. A simple example is @"hello". In a verbatim string literal, the characters between the delimiters are interpreted verbatim, the only exception being a quote-escape-sequence. In particular, simple escape sequences and hexadecimal and Unicode escape sequences are not processed in verbatim string literals. A verbatim string literal may span multiple lines.
其他回答
“@”还有另一个含义:把它放在变量声明的前面可以让你使用保留的关键字作为变量名。
例如:
string @class = "something";
int @object = 1;
我只发现了一两个合理的用途。主要在ASP。当你想做这样的事情时:
<%= Html.ActionLink("Text", "Action", "Controller", null, new { @class = "some_css_class" })%>
这将产生一个HTML链接,如:
<a href="/Controller/Action" class="some_css_class">Text</a>
否则你将不得不使用'Class',这不是一个保留关键字,但大写的'C'不符合HTML标准,只是看起来不正确。
原因很简单。为了表示字符串“string\”,编译器需要“string\\”,因为\是一个转义字符。如果你用@"string\"代替,你就可以忘记" \\ "了。
既然你也明确地要求使用VB,让我补充一下,这种逐字逐句的字符串语法在VB中不存在,只在c#中存在。相反,在VB中,所有字符串都是逐字逐句的(除了它们不能包含换行符,不像c#逐字逐句的字符串):
Dim path = "C:\My\Path"
Dim message = "She said, ""Hello, beautiful world."""
VB中不存在转义序列(除了引号字符的加倍,就像c#中的逐字字符串一样),这使得一些事情更加复杂。例如,要在VB中编写以下代码,您需要使用连接(或任何其他构造字符串的方法)
string x = "Foo\nbar";
在VB中,这将被写成如下:
Dim x = "Foo" & Environment.NewLine & "bar"
(&是VB字符串连接操作符。+也可以同样使用。)
复制自MSDN:
在编译时,逐字字符串被转换为具有所有相同转义序列的普通字符串。因此,如果在调试器监视窗口中查看逐字字符串,将看到编译器添加的转义字符,而不是源代码中的逐字版本。例如,逐字字符串@"C:\files.txt"将以"C:\\files.txt"的形式出现在监视窗口中。
将@放在字符串前面可以使用特殊字符,如反斜杠或双引号,而不必使用特殊代码或转义字符。
所以你可以这样写:
string path = @"C:\My path\";
而不是:
string path = "C:\\My path\\";