【发布时间】:2016-07-28 14:34:47
【问题描述】:
我正在尝试在我的一种方法中灵活地使用IDictionary 接口,但由于转换方面的限制(请参阅C# type conversion: Explicit cast exists but throws a conversion error?),它的使用对我来说非常有限。我想知道是否有一些解决方法。
这是我的具体问题: 我有一个方法,它采用将每个键映射到其他键的 IEnumerable 的映射。它也需要一键作为输入。它的作用是找到给定键的关于映射的闭包集/外壳:
public static ISet<T> GetClosureSet(T element, IDictionary<T, IEnumerable<T>> elementToCollectionMap)
{
ISet<T> closure = new HashSet<T>();
closure.Add(element);
closure.UnionWith(elementToCollectionMap[element]);
int count = 0;
while (count != closure.Count)
{
count = closure.Count;
foreach (T elem in new HashSet<T>(closure))
closure.UnionWith(elementToCollectionMap[elem]);
}
return closure;
}
IDictionary<double, IEnumerable<double>> 类型的此类映射示例:
1 -> [2, 3, 4]
2 -> [3, 7]
3 -> [3]
4 -> [] // empty enumerable, i.e. array of length 0
5 -> [6]
6 -> [6]
7 -> []
如果我将密钥1 和这个映射放入我的方法中,我将得到[1, 2, 3, 4, 7]:首先将1 及其图像[2, 3, 4] 放入闭包集中。然后1、2、3、4的图像也被添加,所以我们也得到7(作为2图像的元素)。在下一步中,1、2、3 的所有图像
、4、7 已添加,但它们已经存在。因此,该方法结束并返回。
如您所见,这是一个非常抽象的方法,它并不关心值的真正含义。只需要将值设为IEnumerable<T> 即可调用UnionWith。
但是现在我希望能够在我有从键到某种键集合的映射时使用该方法!
我的代码中有一些地方是我定义的
IDictionary<MyType, HashSet<MyType>> foo = new Dictionary<MyType, HashSet<MyType>>();
和
IDictionary<MyType, List<MyType>> bar = new Dictionary<MyType, List<MyType>>();
并且需要它们真正成为IDictionary<MyType, HashSet<MyType>> 和IDictionary<MyType, List<MyType>>,因为我需要HashSet 和List 的一些功能,而不是IEnumerable 提供的功能。只有稍后我才想要关闭。但就像现在一样,我不能将 foo 和 bar 作为我的方法的输入 - 我需要从它们创建新字典以适应类型。
关于如何解决问题的任何想法(我不认为“创建一个新字典以适应类型”是一种解决方案)?
【问题讨论】:
标签: c# dictionary interface type-conversion