2014-04-01 210 views
2

我有下面的代码,它使用一个像这样的字符串:字符串连接和@

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); 
+1

你说的“我仍然需要使用‘@’”是什么意思?你得到什么错误? – helb

+1

string str = String.Format(“这是非常重要的字符串,它使用{0}”,name);是格式化字符串的更好选择 –

回答

6

你每天字符串字面(只有文字,没有变量),如果你想治疗字面转义序列之前使用@。所以你的情况,你只需要做到:

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

BTW,使用@"this is very important string ,which uses "不会有所作为,因为它没有任何转义序列。

进一步了解verbatim string literals on MSDN

逐字字符串由一个@字符后跟一个双引号字符,零个或多个字符,并且结束的双引号字符的。一个简单的例子是@“你好”。在逐字字符串文字中,分隔符之间的字符是逐字解释的,唯一的例外是引号转义序列。特别是,简单字符串文字中不处理简单转义序列和十六进制和Unicode转义序列。逐字字符串文字可能跨越多行。

因此,当@有差别可能是制表符\t一个例子:

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