[英]Store a short string
我在代碼中有很多提示,每個提示都是一個字符串,例如“ welcome to our company”或“ goodby”等。
現在,我要管理這些提示。 有兩種方法,一種是將每個字符串存儲在文件中,然后將其加載到代碼中。
private string LoadPrompt(string inid, string PromptsPath,string promptFile)
{
StringBuilder filetopen = new StringBuilder();
StringBuilder content = new StringBuilder();
filetopen.Append(PromptsPath + inid + "_" + promptFile);
try
{
if (File.Exists(filetopen.ToString()))
{
using (StreamReader reader = File.OpenText(filetopen.ToString()))
{
string line;
while ((line = reader.ReadLine()) != null)
{
content.Append(line);
}
}
}
}
catch (Exception ex)
{
AppLogEx(ex, "Utilities:LoadPrompt");
content.Clear();
content.Append("ERROR");
}
return content.ToString();
}
另一個是在app.config中放置提示。 哪種方法更好,更快地加載它們?
將字符串設置為Resources 。
在平面文件或app.config上使用資源的好處是,您可以將字符串本地化為各種語言,並且提供了支持和工具,可以使此過程變得更加容易。 如果提供多種語言,則程序可以根據本地系統自動選擇適當的語言/區域性,而無需執行任何其他工作。
關於代碼,您可以這樣做更簡單
代替
using (StreamReader reader = File.OpenText(filetopen.ToString()))
{
string line;
while ((line = reader.ReadLine()) != null)
{
content.Append(line);
}
}
你可以寫
File.ReadAllLines(filetopen.ToString())
.ToList() - added only for Foreach, I think you've your own Foreach extension for IEnumerable
.ForEach(x => content.AppendLine(x));
關於提示,配置或資源
好吧,如果您通過app.config進行操作,則它實際上是一個XML文件。 這樣您就可以很容易地找到正確的提示。 由於它是一個設置文件,因此可以在其中存儲您可能會更改的所有設置。 您可以使用常規文本文件執行相同的操作,但是隨后您需要以某種方式標記不同的提示...在這種情況下,最好使用XML。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.