AFAIK,当KEY 是要存储的VALUE 的类型时,此通用集合仅用作KeyedCollection<KEY,VALUE> 的简单包装器。
例如,如果你想实现工厂返回单例,使用这个集合非常方便:
public class Factory<T>
{
private readonly KeyedByTypeCollection<T> _singletons = new KeyedByTypeCollection<T>();
public V GetSingleton<V>() where V : T, new()
{
if (!_singletons.Contains(typeof(V)))
{
_singletons.Add(new V());
}
return (V)_singletons[typeof(V)];
}
}
这个简单工厂的用法如下:
[Test]
public void Returns_Singletons()
{
Factory<ICar> factory = new Factory<ICar>();
Opel opel1 = factory.GetSingleton<Opel>();
Opel opel2 = factory.GetSingleton<Opel>();
Assert.IsNotNull(opel1);
Assert.IsNotNull(opel2);
Assert.AreEqual(opel1, opel2);
}
KeyedByTypeCollection<T> 的另一种用法是在服务定位器中...