我已经看到了与字符串生成器有关的问题,但是找不到相关的答案。
我的问题是“在这里使用字符串生成器是否明智?如果不是在此处明智地使用它”。
此方法将运行100000次。为了节省一些内存,我在这里使用了stringbuilder。但是问题是.ToString()方法。无论如何,我将不得不使用.ToString()method 创建一个字符串,所以为什么不初始化filename为string而不是StringBuilder。
internal bool isFileExists()
{
StringBuilder fileName = new StringBuilder(AppDomain.CurrentDomain.BaseDirectory + "Registry\\" + postalCode + ".html");
if (System.IO.File.Exists(fileName.ToString()))
{
return true;
}
else
{
return false;
}
}
Run Code Online (Sandbox Code Playgroud)
所有库方法都使用字符串作为参数,而不是字符串生成器,为什么?我觉得我的概念很混乱。
实际上您没有使用字符串生成器。您首先通过以下方式创建一个字符串:
AppDomain.CurrentDomain.BaseDirectory + "Registry\\" + postalCode + ".html"
Run Code Online (Sandbox Code Playgroud)
然后将其提供给字符串生成器。
正确使用StringBuilder:
StringBuilder fileName = new StringBuilder();
fileName.Append(AppDomain.CurrentDomain.BaseDirectory);
fileName.Append("Registry\\");
fileName.Append(postalCode );
fileName.Append(".html");
Run Code Online (Sandbox Code Playgroud)
如果你制作衬垫来制作琴弦,你可以通过以下方式制作琴弦:
string filenamestr = AppDomain.CurrentDomain.BaseDirectory + "Registry\\" + postalCode + ".html";
Run Code Online (Sandbox Code Playgroud)
在这种情况下,您正在创建文件路径,因此建议使用:
Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Registry\\" , postalCode , ".html");
Run Code Online (Sandbox Code Playgroud)