2013-11-21 145 views
1

我有一個控制器,其中我將html文件讀入一個變量。將一個變量的值替換爲另一個值

讀它之後,我從變量爲其他值替換一些值,

但問題是,沒有什麼happend。

這裏有什麼問題?

有人能幫我一個忙嗎?

string path = "/mypath/myfile.html"; 
string s = System.IO.File.ReadAllText(path); 
s.Replace("@%a%@","hi"); 
s.Replace("@%b%@","yo"); 
s.Replace("@%c%@","asdfasdf"); 
s.Replace("@%d%@", "http://www.google.com"); 
+4

.NET中的字符串是不可變的 –

回答

4

字符串是不可變的 - 您應該將替換結果分配給您的字符串。您也可以像這樣的連鎖替換操作:

string s = System.IO.File.ReadAllText(path) 
      .Replace("@%a%@","hi") 
      .Replace("@%b%@","yo") 
      .Replace("@%c%@","asdfasdf") 
      .Replace("@%d%@", "http://www.google.com"); 

只要記住 - 所有的字符串操作(如替換,子串等)將創建並返回新的字符串,而不是改變原來的。這同樣意味着對DateTime和其他不可變對象的操作。

更新:您還可以聲明替換的字典和更新字符串在一個循環:

var replacements = new Dictionary<string, string> { 
    { "@%a%@","hi" }, { "@%b%@","yo" }, { "@%c%@","asdfasdf" } // ... 
}; 

string s = System.IO.File.ReadAllText(path); 

foreach(var replacement in replacements) 
    s = s.Replace(replacement.Key, repalcement.Value); 
+1

是的。你是對的..工作很好..非常感謝你 – user2232273

2

字符串是不可改變的。基本上,一個對象是不可變的,如果它的狀態一旦創建對象就不會改變。因此,如果一個類的實例是不可變的,則它是不可變的。

string path = "/mypath/myfile.html"; 
string s = System.IO.File.ReadAllText(path); 
s = s.Replace("@%a%@","hi"); 
s = s.Replace("@%b%@","yo"); 
s = s.Replace("@%c%@","asdfasdf"); 
s = s.Replace("@%d%@", "http://www.google.com"); 
+0

非常感謝你的答案..它的工作也是如此。 – user2232273

相關問題