用两把钥匙收集

时间:2010-01-25 14:23:12

标签: c# collections

在解决方案中,我已经解决了这个问题=> General type conversion without risking Exceptions(请参阅问题底部的编辑),我需要缓存一种在两种类型之间进行转换的方法。

因此,给定Type1和Type2,我需要检索一个方法。

在回答这个问题时=> What is the best C# collection with two keys and an object?建议使用字典词典。这与我正在做的类似。

但我不喜欢它。它在逻辑上不会与集合所代表的内容相关。还要检索我必须要做的值:

        if ( !_Types.ContainsKey ( s.GetType () ) )
        {
            type1Cache = new Dictionary<Type, ConversionCache> ();

            _Types.Add ( s.GetType (), type1Cache );
        }
        else
        {
            type1Cache = _Types[s.GetType ()];
        }

        if ( !type1Cache.ContainsKey ( value.GetType () ) )
        {
            // We havent converted this type before, so create a new conversion
            type2Cache = new ConversionCache ( s.GetType (), value.GetType () );

            // Add to the cache
            type1Cache.Add ( value.GetType (), type2Cache );
        }
        else
        {
            type2Cache = type1Cache[value.GetType ()];
        }

这有点啰嗦。

我只想做像

这样的事情
        if ( !_Types.ContainsKey ( s.GetType (), value.GetType() ) )
        {
            cache = new ConversionCache ( s.GetType (), value.GetType () );

            _Types.Add ( s.GetType (), value.GetType(), cache);
        }
        else
        {
            cache = _Types[s.GetType (), value.GetType()];
        }

一种解决方案是连接类型的字符串值。类似的东西:

        if ( !_Types.ContainsKey ( s.GetType ().ToString() + ":" +  value.GetType().ToString() ) )
        {
            cache = new ConversionCache ( s.GetType (), value.GetType () );
            _Types.Add ( s.GetType ().ToString() + ":" +  value.GetType().ToString(), cache);
        }
        else
        {
            cache = _Types[s.GetType ().ToString() + ":" +  value.GetType().ToString()];
        }

我知道它会在这个实例中起作用,因为类型和它的字符串表示之间存在一对一的关系。

但那闻起来很糟糕,在其他情况下无法发挥作用。

有更好的方法吗?

2 个答案:

答案 0 :(得分:2)

您可能需要以前版本中的Tuples(在.Net 4中)或一个众所周知的“Pair”类:KeyValuePair。

但是 - 考虑到你的要求,我可能会选择自定义课程。你可以确保hashcode / equals做你想要的,可以覆盖ToString()进行合理的日志记录,无论如何它可能读得更好。

答案 1 :(得分:1)

你这样做的方式很好。如果你想要一个更好的“气味”系统,你需要的是一个辅助函数,它接受两个输入(或类型)并返回一个唯一的字符串。然后隐藏生成密钥的实现细节(在这种情况下将它们与“:”分隔符连接)。

对我来说似乎有点过度工程。我不相信您有太多机会需要更改此密钥生成方法,而您并不是要创建泛型类。显然,您需要使用泛型类。