.Net中KeyedByTypeCollection的使用?

Bis*_*ath 9 .net .net-3.5

在.net中查看泛型集合时,我发现了KeyedByTypeCollection.虽然我使用它并且知道如何使用它,但我没有得到它会有用的情况.

我通过ServiceProvider,缓存等阅读了没有强制转换的泛型,但是得不到多少.

我认为,必须有一个理由说明为什么它被包含在.Net框架中.使用KeyedByTypeCollection的任何团体都可以解释为什么他们使用它或任何身体,如果他们知道可以使用哪种情况,可以向我解释.

更多的好奇心是否有其他语言支持这种类型的收藏?

Pre*_*sen 13

AFAIK,这个泛型集合只是一个简单的包装器,用于KeyedCollection<KEY,VALUE>何时存储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)];
    }
}
Run Code Online (Sandbox Code Playgroud)

使用这个简单的工厂将类似于以下内容:

    [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);
    }
Run Code Online (Sandbox Code Playgroud)

另一种用法KeyedByTypeCollection<T>是在服务定位器内......