System.Collections.IEnumerable 的 LINQ

Sim*_*mon 4 c# linq unity-game-engine

LINQ可以使用Where()System.Collections.Generic.IEnumerable<T>但如果实现的接口是System.Collections.IEnumerable

我的问题是,为什么会这样?

更新: 也许有点上下文,我想.Where()TransformUnity的类上使用,它实现System.Collections.IEnumerable而不是System.Collections.Generic.IEnumerable<Transform>即使它只有Transforms子级......所以我现在创建了一个扩展方法Transform,随意使用它:

/// <summary> Where-Filter implementation for transform to filter out specific children</summary>
public static IEnumerable<GameObject> WhereChild(this Transform s, Func<GameObject, bool> callback) {
    List<GameObject> r = new List<GameObject>();
    foreach (Transform cur in s) { if (callback(cur.gameObject)) { r.Add(cur.gameObject); } }
    return r;
}
Run Code Online (Sandbox Code Playgroud)

(如果你想处理变换而不是子游戏对象,请修改它,我更喜欢这种方式;)

Joe*_*oey 5

因为这些方法中的大多数都是通用的,当你只得到objects时几乎没有意义。有几个方法在事实上宣告作为扩展方法IEnumerable代替IEnumerable<T>,如Cast<T>()OfType<T>,这两者的返回类型枚举。

因此,在您的情况下,您可以使用Cast<object>()以最无用的方式获得 LINQ 的好处,因为 for 谓词Where不能真正合理地做很多事情,object而没有强制转换它。