在我们的应用程序中,我们有一些来自翻译的字符串可以包含变量。例如在Can i have a {beverage}?
中{beverage}
部分应该用变量替换。 我的当前实现通过使用所有变量的名称和值的字典,并只替换正确的字符串。不过,我想通过引用来注册变量,以便如果值被更改,结果字符串也会被更改。通常传递一个带有ref
关键字的参数可以做到这一点,但我不确定如何将这些参数存储在字典中。参考字典值
TranslationParser:
static class TranslationParser
{
private const string regex = "{([a-z]+)}";
private static Dictionary<string, object> variables = new Dictionary<string,object>();
public static void RegisterVariable(string name, object value)
{
if (variables.ContainsKey(name))
variables[name] = value;
else
variables.Add(name, value);
}
public static string ParseText(string text)
{
return Regex.Replace(text, regex, match =>
{
string varName = match.Groups[1].Value;
if (variables.ContainsKey(varName))
return variables[varName].ToString();
else
return match.Value;
});
}
}
main.cs
string bev = "cola";
TranslationParser.RegisterVariable("beverage", bev);
//Expected: "Can i have a cola?"
Console.WriteLine(TranslationParser.ParseText("Can i have a {beverage}?"));
bev = "fanta";
//Expected: "Can i have a fanta?"
Console.WriteLine(TranslationParser.ParseText("Can i have a {beverage}?"));
这是不可能的,还是我只是接近正确的问题?我担心唯一的解决方案会涉及不安全的代码(指针)。
因此,简而言之,我想将一个变量存储在字典中,更改原始变量并从字典中获取已更改的值。就像你会用ref
关键字一样。
http://en.wikipedia.org/wiki/Rope_(computer_science)可能会感兴趣。 – 2012-04-27 11:51:06
@DaveBish你是一个快速读者!但那篇文章似乎是关于存储,这不是一个问题。这些字符串来自xml文件,并且不包含在二进制文件中。 – TJHeuvel 2012-04-27 11:52:27
和字符串操作似乎很好,我只是想基本上存储在字典中的参考。 – TJHeuvel 2012-04-27 11:55:44