2014-04-01 213 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