在SO上也有类似的问题,但没有一个回答我的问题。
我想要有二维字典进行翻译。像这样:
Dictionary["DE"][TranslationKeys.Title] = "Title in German";
Dictionary["DE"][TranslationKeys.SubTitle] = "Subtitle in German";
Dictionary["PL"][TranslationKeys.Title] = "Title in Polish";
Dictionary["PL"][TranslationKeys.SubTitle] = "Subtitle in Polish";
Dictionary["EN"][TranslationKeys.Title] = "Title in English";
Dictionary["EN"][TranslationKeys.SubTitle] = "Subtitle in English";
如果我使用像Dictionary<string,Dictionary<TranslationKeys,string>>
但我不想要以“丑陋”的方式初始化它:
Dictionary = new Dictionary<string,Dictionary<TranslationKeys,string>>(){
{"PL",new Dictionary<TranslationKeys,string>(){{TranslationKeys.SubTitle,"Subtitle in Polish"}}}
};
但是像这样:
Dictionary["PL"][TranslationKeys.SubTitle] = "Subtitle in Polish";
所以我试图实现一个“智能”的多维字典,如果他得到了价值,就能弄明白自己。我到目前为止所做的是一个使用Dictionary和特殊索引器的新泛型类:
public class TranslateDictionary<TKey, TValue> where TValue : new()
{
private Dictionary<TKey, TValue> Dictionary;
public TValue this[TKey lang]
{
get
{
if (!Dictionary.ContainsKey(lang))
{
TValue obj = new TValue();
Dictionary.Add(lang, new TValue());
}
return Dictionary[lang];
}
set
{
Dictionary[lang] = value;
}
}
}
但现在我被卡住了...因为我在我的泛型类型TranslateDictionary中使用字符串我得到了这个错误:
错误2'string'必须是具有公共无参数构造函数的非抽象类型,才能在泛型类型或方法'Resources.TranslateDictionary'
中将其用作参数'TValue'
Allthough编译器不会抱怨这样的初始化:
Dictionary["EN"][TranslationKeys.Title] = "Title in English";
也许我应该使用其他类型的集合而不是我不知道的字典来解决我的问题?
答案 0 :(得分:4)
我做到了。我只需稍微改变我的索引器。以下是实现这项工作的方法:
public class TranslateDictionary<TKey, TValue>
{
private Dictionary<TKey, TValue> Dictionary = new Dictionary<TKey,TValue>();
public TValue this[TKey lang]
{
get
{
if (!Dictionary.ContainsKey(lang))
{
Dictionary.Add(lang, Activator.CreateInstance<TValue>());
}
return Dictionary[lang];
}
set
{
Dictionary[lang] = value;
}
}
}
现在你有了
TranslateDictionary<string, TranslateDictionary<TranslationKeys, string>> Dictionary { get; set; }
您只需要创建字典的实例:
Dictionary = new TranslateDictionary<string, TranslateDictionary<TranslationKeys, string>>();
你可以自由地初始化它的元素:
Dictionary["PL"][TranslationKeys.SubTitle] = "SubTitle in Polish";
Dictionary["EN"][TranslationKeys.SubTitle] = "SubTitle in English";
Dictionary["DE"][TranslationKeys.SubTitle] = "SubTitle in German";
也许这种方法比普通字典慢,因为每当你尝试读取值时检查内部字典是否包含键,但至少你可以用“更清洁”的方式为它分配元素。
<强>更新强> 我已经升级了我的TranslateDictionary了一点。我添加了布尔属性“Initialized”。现在,在初始化之后,我可以将此值设置为“true”,并且不会再检查字典中是否存在值。它会更像正常的Dictioanry类型。
public class TranslateDictionary<TKey, TValue>
{
public bool Initialized { get; set; }
private Dictionary<TKey, TValue> Dictionary = new Dictionary<TKey,TValue>();
public TValue this[TKey lang]
{
get
{
if (!Initialized)
{
if (!Dictionary.ContainsKey(lang))
{
Dictionary.Add(lang, Activator.CreateInstance<TValue>());
}
}
return Dictionary[lang];
}
set
{
Dictionary[lang] = value;
}
}
}