简体   繁体   English

字符串串联和@

[英]String concatenation and @

I have the following code which uses a string like this : 我有以下代码使用这样的字符串:

string str = @"this is very important string ,which uses hardcoded name";

I want to change it to have a value of input argument 我想将其更改为具有输入参数的值

public void func (string name)
{
    // some code
    string str = "this is very important string ,which uses " + name;
}

When I generate the string I still need to use "@" what can I do? 当我生成字符串时,我仍然需要使用“ @”怎么办?

string str = @("this is very important string ,which uses " + name);

You use @ before every string literal (and only literals, not variables) if you want to treat escape sequences literally. 如果要按字面意义对待转义序列,则在每个字符串文字 (且仅文字,而不是变量)之前使用@ So in your case, you only need to do: 因此,在您的情况下,您只需要执行以下操作:

string str = @"this is very important string ,which uses " + name;

BTW, using @ for "this is very important string ,which uses " won't make a difference as it doesn't have any escape sequences. 顺便说一句,使用@表示"this is very important string ,which uses "不会有任何区别,因为它没有任何转义序列。

More about verbatim string literals on MSDN : 有关MSDN上的逐字字符串文字的更多信息:

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". 一个简单的例子是@“ 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. 特别是,简单的转义序列以及十六进制和Unicode转义序列不在逐字字符串文字中处理。 A verbatim string literal may span multiple lines. 逐字字符串文字可能跨越多行。

Thus an example where @ makes a difference may be for the tab character \\t : 因此, @会有所不同的示例可能是制表符\\t

string c = "hello \t world";    // hello     world <-- tab here
string d = @"hello \t world";   // hello \t world <-- treated literally

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM