字符串串联和@

亚科夫

我有以下代码使用这样的字符串:

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

我想将其更改为具有输入参数的值

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

当我生成字符串时,我仍然需要使用“ @”怎么办?

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

如果要按字面意义对待转义序列,则可以@在每个字符串文字使用(并且仅在文字上使用,而不是变量)。因此,在您的情况下,您只需要执行以下操作:

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

顺便说一句,使用@for"this is very important string ,which uses "不会有任何区别,因为它没有任何转义序列。

有关MSDN上的逐字字符串文字的更多信息

逐字字符串文字包含一个@字符,后跟一个双引号字符,零个或多个字符以及一个结束的双引号字符。一个简单的例子是@“ hello”。在逐字字符串文字中,定界符之间的字符逐字解释,唯一的例外是引号-转义序列。特别是,简单的转义序列以及十六进制和Unicode转义序列不在逐字字符串文字中处理。逐字字符串文字可以跨越多行。

因此@,制表符可能有所作为的一个示例\t

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章