如果你擔心性能,手動解析在單次的模板可能是最快的,你可以去:
static string DictFormat(string template, IDictionary<string, string> dict) {
const string left_delimiter = "{$";
int left_delimiter_len = left_delimiter.Length;
const string right_delimiter = "}";
int right_delimiter_len = right_delimiter.Length;
var sb = new StringBuilder();
int end = 0;
while (true) {
int start = template.IndexOf(left_delimiter, end);
if (start >= 0) {
sb.Append(template.Substring(end, start - end));
start += left_delimiter_len;
end = template.IndexOf(right_delimiter, start);
if (end >= 0) {
string key = template.Substring(start, end - start);
string value;
if (dict.TryGetValue(key, out value)) {
sb.Append(value);
end += right_delimiter_len;
}
else
throw new ArgumentException(string.Format("Key not found: {0}", key), "template");
}
else
throw new ArgumentException(string.Format("Key starting at {0} not properly closed.", start), "template");
}
else {
sb.Append(template.Substring(end));
return sb.ToString();
}
}
}
使用方法如下:
const string template = "hello {$name}. you are {$age} years old. you live in {$location}";
var dict = new Dictionary<string, string> { { "name", "spender" }, { "age", "38" }, { "location", "UK" } };
string result = DictFormat(template, dict);
請問是什麼這種情況迫使你這樣做,而不是一個「正常」的字符串。格式? –
@BrankoDimitrijevic:一堆用戶可編輯的電子郵件模板 – spender