如何获得ReadOnlyCollection还< T> T,S>该键在Dictionary<的;

如何获得ReadOnlyCollection还< T> T,S>该键在Dictionary<的;

问题描述:

我的类包含一个词典&LT; T,S&GT;字典,我要揭露一个 ReadOnlyCollection还&LT; T&GT; 的关键。我怎么能做到这一点不复制词典&LT; T,S&GT; .KeyCollection dict.Keys 到一个数组,然后露出了数组作为 ReadOnlyCollection还

My class contains a Dictionary<T, S> dict, and I want to expose a ReadOnlyCollection<T> of the keys. How can I do this without copying the Dictionary<T, S>.KeyCollection dict.Keys to an array and then exposing the array as a ReadOnlyCollection?

我要的 ReadOnlyCollection还是一个合适的包装,即得。以反映底层词典变化,据我了解复制集合到一个数组是不会这样做的(以及低效似乎 - 我其实不愿意一个新的集合,只是揭露键底层集合.. )。任何想法,将不胜感激。

I want the ReadOnlyCollection to be a proper wrapper, ie. to reflect changes in the underlying Dictionary, and as I understand it copying the collection to an array will not do this (as well as seeming inefficient - I don't actually want a new collection, just to expose the underlying collection of keys...). Any ideas would be much appreciated!

编辑:我使用C#2.0,因此不具备扩展方法,如.ToList(容易)可用。

I'm using C# 2.0, so don't have extension methods such as .ToList (easily) available.

如果你真的想使用ReadOnlyCollection还&LT; T>中,问题是,ReadOnlyCollection还与LT的构造; T&GT;需要一个IList&LT; T&GT ;,而词典的KeyCollection只是一个ICollection的&LT; T&GT;

If you really want to use ReadOnlyCollection<T>, the issue is that the constructor of ReadOnlyCollection<T> takes an IList<T>, while the KeyCollection of the Dictionary is only a ICollection<T>.

所以,如果你想换行KeyCollection在ReadOnlyCollection还你将不得不创建一个适配器(或包装)类型,实施的IList&LT; T&GT ;,包裹KeyCollection。因此,它看起来像:

So if you want to wrap the KeyCollection in a ReadOnlyCollection, you'll have to create an adapter (or wrapper) type, implementing IList<T>, wrapping the KeyCollection. So it would look like:

var dictionary = ...;
var readonly_keys = new ReadOnlyCollection<T> (new CollectionListWrapper<T> (dictionary.Keys)
);



不是很优雅,虽然,特别是作为KeyCollection已经是一个只读集合,你可以简单地传递围绕它作为一个ICollection的&LT; T&GT; :)

Not very elegant though, especially as the KeyCollection is already a readonly collection, and that you could simply pass it around as an ICollection<T> :)