gpt4 book ai didi

c# - 优化我的方法

转载 作者:太空宇宙 更新时间:2023-11-03 17:16:42 25 4
gpt4 key购买 nike

我正在尝试创建一个实用程序方法来对模板文件执行类似邮件合并的功能。由于字符串是不可变的,我不确定我是否正确编写了它 - 有人可以看一眼并给我反馈吗?

public static string LoadTemplateFile(string fileName, 
NameValueCollection mergeFields)
{
string result = System.IO.File.ReadAllText(fileName);

if (mergeFields != null)
{
for (int index = 0; index < mergeFields.Count; index++)
{
result = result.Replace(mergeFields.Keys[index],
mergeFields[index]);
}
}

return result;
}

最佳答案

您可能最好使用 StringBuilder 而不是字符串。

public static string LoadTemplateFile(
string fileName, NameValueCollection mergeFields)
{
System.Text.StringBuilder result = new System.Text.StringBuilder(
System.IO.File.ReadAllText(fileName));

if (mergeFields != null)
{
for (int index = 0; index < mergeFields.Count; index++)
{
result.Replace(mergeFields.Keys[index],
mergeFields[index]);
}
}

return result.ToString();
}

关于c# - 优化我的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/744203/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com