我有一个复杂的数据容器,具有多个嵌套词典。
但是具有Key
和Value
属性使其不直觉且难以使用。
请建议在Dictionary<,>
子类中重命名键和值属性的最简单方法。
更新:
patryk®Wiek:如果您实现IDictionary<TKey, TValue>
,您也无法重命名属性,因为它们是合同的一部分。
你是对的。我的问题不正确。在IDictionary
中使用KeyValuePair
将对属性限制为Key
和Value
。因此,如果我们想要非密钥/值对,我们必须使用自定义KeyValuePair
结构实现IDictionary
。还是还有其他一些棘手的方法?
ps。也许有人建议IDictionary
代码生成模板?
与所需的属性名称制作自己的接口。然后,让您的具体类实现您的自定义接口。
要保持代码干燥,请创建一个私人词典,您将所有工作委派给。您甚至可以通过将所需方法委派给您的私人变量来枚举自定义接口(或IDictionary
实施的其他任何内容)。
这是一个示例。您只需要将代码从使用IDictionary
更改为IComplexDataContainer
。
interface IComplexDataContainer<TKey, TValue>
: IEnumerable<KeyValuePair<TKey,TValue>>
{
TValue this[TKey index] { get; set; }
}
class MyComplexDataContainer<TKey, TValue>
: IComplexDataContainer<TKey, TValue>
{
IDictionary<TKey, TValue> hiddenHelper { get; set; }
public MyComplexDataContainer()
{
hiddenHelper = new Dictionary<TKey, TValue>();
}
// delegate all of the work to the hidden dictionary
public TValue this[TKey index]
{
get
{
return hiddenHelper[index];
}
set
{
hiddenHelper[index] = value;
}
}
// Just delegate the IEnumerable interface to your hidden dictionary
// or any other interface you want your class to implement
public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator()
{
return hiddenHelper.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
然后您只会这样使用:
IComplexDataContainer<string, int> myData = new MyComplexDataContainer<string,int>();
myData["tom"] = 18;
myData["dick"] = 22;
myData["harry"] = myData["tom"];