通用 NameValueCollection
NameValueCollection 与 Dictionary 不同的特点是,一个键可以包含多个元素。
以下代码基于 NameObjectCollectionBase 实现了通用的 NameValueCollection<T>:
using System.Collections.Specialized;
namespace System.Collections.Generic
{
public class NameValueCollection<T> : NameObjectCollectionBase
{
private string[] _keys;
private T[] _values;
protected void InvalidateCachedArrays()
{
_values = null;
_keys = null;
}
protected static T[] AsArray(ArrayList list)
{
int count = 0;
if (list == null || (count = list.Count) == 0)
return (T[])null;
T[] array = new T[count];
list.CopyTo(0, array, 0, count);
return array;
}
protected ArrayList GetAllValues()
{
int count = Count;
ArrayList arrayList = new ArrayList(count);
for (int i = 0; i < count; ++i)
{
arrayList.AddRange(Get(i));
}
return arrayList;
}
public void Add(string name, T value)
{
InvalidateCachedArrays();
ArrayList arrayList = (ArrayList)BaseGet(name);
if (arrayList == null)
{
arrayList = new ArrayList(1);
if (value != null) arrayList.Add(value);
BaseAdd(name, arrayList);
}
else
{
if (value == null) return;
arrayList.Add(value);
}
}
public void Add(NameValueCollection<T> collection)
{
InvalidateCachedArrays();
int count = collection.Count;
for (int i = 0; i < count; i++)
{
string key = collection.GetKey(i);
T[] values = collection.Get(i);
foreach (var value in values)
{
Add(key, value);
}
}
}
public void Set(string name, T value)
{
InvalidateCachedArrays();
BaseSet(name, new ArrayList(1) { value });
}
public void Set(string name, params T[] values)
{
InvalidateCachedArrays();
BaseSet(name, new ArrayList(values));
}
public T[] Get(string name)
{
return AsArray((ArrayList)BaseGet(name));
}
public T[] Get(int index)
{
return AsArray((ArrayList)BaseGet(index));
}
public string GetKey(int index)
{
return BaseGetKey(index);
}
public void Remove(string name)
{
InvalidateCachedArrays();
BaseRemove(name);
}
public void Clear()
{
InvalidateCachedArrays();
BaseClear();
}
public new string[] Keys
{
get
{
if (_keys == null)
_keys = BaseGetAllKeys();
return _keys;
}
}
public T[] Values
{
get
{
if (_values == null)
_values = AsArray(GetAllValues());
return _values;
}
}
public T[] this[int index]
{
get
{
return Get(index);
}
set
{
BaseSet(index, new ArrayList(value));
}
}
public T[] this[string name]
{
get
{
return Get(name);
}
set
{
BaseSet(name, new ArrayList(value));
}
}
public IEnumerable<KeyValuePair<string, T>> GetAllEntries()
{
foreach (string key in Keys)
{
foreach (T value in Get(key))
{
yield return new KeyValuePair<string, T>(key, value);
}
}
}
}
}
使用方法:
NameValueCollection<int> collection = new NameValueCollection<int>();
collection.Add("a", 123);
collection.Add("a", 456);
collection.Add("b", 789);
int[] a = collection.Get("a");
int[] b = collection.Get("b");
以上代码实现了主要功能。
这里是实现 NameValueCollection<T> 的完整代码,包含额外的工具。