Why do so many named collections in .NET not implement IEnumerable?

后端 未结 2 1123
佛祖请我去吃肉
佛祖请我去吃肉 2021-02-20 00:43

Random example:

ConfigurationElementCollection

.Net has tons of these little WhateverCollection classes that don\'t implement

相关标签:
2条回答
  • 2021-02-20 01:37

    The answer is in the question title: "named collections". Which is the way you had to make collections type-safe before generics became available. There are a lot of them in code that dates back to .NET 1.x, especially Winforms. There was no reasonable way to rewrite them using generics, that would have broken too much existing code.

    So the named collection type is type safe but the rub is System.Collections.IEnumerator.Current, a property of type Object. You can Linqify these collections by using OfType() or Cast().

    0 讨论(0)
  • 2021-02-20 01:41

    As Adam Houldsworth said in a comment already, you simply need to use the Cast<> method.

    Example:

    var a = new DogCollection();
    var allFidos = a.Cast<Dog>().Where(d => d.Name == "Fido"); 
    
    0 讨论(0)
提交回复
热议问题