代码之家  ›  专栏  ›  技术社区  ›  Mongus Pong

带两个钥匙的收藏

  •  2
  • Mongus Pong  · 技术社区  · 15 年前

    在解决方案中,我已经解决了这个问题=> 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 回复  |  直到 15 年前
        1
  •  1
  •   Hogan    15 年前

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

    在我看来有点过于工程化了。我不认为你有太多的机会需要改变这个密钥生成方法,你也没有试图创建一个通用类。显然,您需要使用一个泛型类来完成这项工作。

        2
  •  2
  •   Benjamin Podszun    15 年前

    您可能需要tuples(在.NET 4中)或以前版本中一个众所周知的“pair”类:keyValuePair。

    但是,考虑到你的要求,我可能会去上一个定制课。您可以确保hashcode/equals执行您想要的操作,可以重写toString()以实现明智的日志记录,而且它的读取效果可能会更好。

    推荐文章