在解决方案中,我已经解决了这个问题=> 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()];
}
我知道它在这种情况下会起作用,因为类型与其字符串表示形式之间存在一对一的关系。
但这闻起来很糟糕,并且在其他情况下不起作用。
有更好的方法吗?
最佳答案
您可能需要元组(在 .Net 4 中)或以前版本中一个众所周知的“Pair”类:KeyValuePair。
但是 - 考虑到您的要求,我可能会选择自定义类(class)。您可以确保 hashcode/equals 执行您想要的操作,可以覆盖 ToString() 以进行合理的日志记录,而且无论如何它读起来可能会更好。
关于c# - 有两把 key 的收藏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2132872/