Joe*_* Gö 7 c# generics collections dictionary c#-2.0
我的类包含一个Dictionary<T, S> dict,我想公开一个ReadOnlyCollection<T>键.如何在不复制Dictionary<T, S>.KeyCollection dict.Keys数组然后将数组暴露为数组的情况下执行此操作ReadOnlyCollection?
我希望它 ReadOnlyCollection是一个合适的包装器,即.反映基础字典中的变化,据我所知,将集合复制到数组将不会这样做(以及看似效率低下 - 我实际上并不想要新的集合,只是为了公开基础的密钥集合.. ).任何想法将不胜感激!
编辑:我正在使用C#2.0,因此没有.ToList(轻松)可用的扩展方法.
如果你真的想使用ReadOnlyCollection <T>,问题是ReadOnlyCollection <T>的构造函数采用IList <T>,而Dictionary的KeyCollection只是ICollection <T>.
因此,如果要将KeyCollection包装在ReadOnlyCollection中,则必须创建一个适配器(或包装器)类型,实现IList <T>,包装KeyCollection.所以它看起来像:
var dictionary = ...;
var readonly_keys = new ReadOnlyCollection<T> (new CollectionListWrapper<T> (dictionary.Keys)
);
Run Code Online (Sandbox Code Playgroud)
虽然不是很优雅,特别是因为KeyCollection已经是一个只读集合,你可以简单地传递它作为ICollection <T> :)
DrJokepu说可能很难为Keys Collection实现一个包装器.但是,在这种特殊情况下,我认为实现并不那么困难,因为正如我们所知,这是一个只读包装器.
这允许我们忽略一些在其他情况下难以实现的方法.
这是Dictionary.KeyCollection的包装器的快速实现:
class MyListWrapper<T, TValue> : IList<T>
{
private Dictionary<T, TValue>.KeyCollection keys;
public MyListWrapper(Dictionary<T, TValue>.KeyCollection keys)
{
this.keys = keys;
}
#region IList<T> Members
public int IndexOf(T item)
{
if (item == null)
throw new ArgumentNullException();
IEnumerator<T> e = keys.GetEnumerator();
int i = 0;
while (e.MoveNext())
{
if (e.Current.Equals(item))
return i;
i++;
}
throw new Exception("Item not found!");
}
public void Insert(int index, T item)
{
throw new NotImplementedException();
}
public void RemoveAt(int index)
{
throw new NotImplementedException();
}
public T this[int index]
{
get
{
IEnumerator<T> e = keys.GetEnumerator();
if (index < 0 || index > keys.Count)
throw new IndexOutOfRangeException();
int i = 0;
while (e.MoveNext() && i != index)
{
i++;
}
return e.Current;
}
set
{
throw new NotImplementedException();
}
}
#endregion
#region ICollection<T> Members
public void Add(T item)
{
throw new NotImplementedException();
}
public void Clear()
{
throw new NotImplementedException();
}
public bool Contains(T item)
{
return keys.Contains(item);
}
public void CopyTo(T[] array, int arrayIndex)
{
keys.CopyTo(array, arrayIndex);
}
public int Count
{
get { return keys.Count; }
}
public bool IsReadOnly
{
get { return true; }
}
public bool Remove(T item)
{
throw new NotImplementedException();
}
#endregion
#region IEnumerable<T> Members
public IEnumerator<T> GetEnumerator()
{
return keys.GetEnumerator();
}
#endregion
#region IEnumerable Members
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return keys.GetEnumerator();
}
#endregion
}
Run Code Online (Sandbox Code Playgroud)
这可能不是这些方法的最佳实现:)但它只是为了证明这可能已经完成.
| 归档时间: |
|
| 查看次数: |
6538 次 |
| 最近记录: |