【发布时间】:2010-01-25 14:23:11
【问题描述】:
在我为这个问题制定的解决方案中 => 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()];
}
我知道它会在这种情况下工作,因为类型与其字符串表示之间存在一对一的关系。
但这闻起来很糟糕,在其他情况下也行不通。
有没有更好的方法来做到这一点?
【问题讨论】:
标签: c# collections