我有一个 Controller ,我可以在其中将 html 文件读入变量。
阅读后我将变量中的一些值替换为其他值,
但问题是什么也没发生。
这里有什么问题吗?
有人可以帮助我吗?
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");
最佳答案
字符串是不可变的——您应该将替换结果分配给您的字符串。您也可以像这样链接替换操作:
string s = System.IO.File.ReadAllText(path)
.Replace("@%a%@","hi")
.Replace("@%b%@","yo")
.Replace("@%c%@","asdfasdf")
.Replace("@%d%@", "http://www.google.com");
请记住 - 所有字符串操作(如替换、子字符串等)都将创建并返回新字符串,而不是更改原始字符串。同样意味着对 DateTime 和其他不可变对象(immutable对象)的操作。
更新:您还可以在循环中声明替换字典和更新字符串:
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);
关于c# - 将值从变量替换为另一个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20126496/