Enumerable.OfType <>()与路由集合无法正常工作

kam*_*cus 5 c# linq linq-to-objects

我发誓这没有意义.

鉴于我有HttpRouteCollection来自Web API的这个,我基于一些自定义路由类型进行过滤,特别是IAttributeRoute.我用,httpRoutes.OfType<IAttributeRoute>()但循环表现得像没有元素.

要清楚,当这个循环被击中时,整个集合都是HttpAttributeRoute直接实现的类型IAttributeRoute.此外,我在常规操作上有相同的循环操作RouteCollection.

这不起作用:

foreach (IAttributeRoute route in GlobalConfiguration.Configuration.Routes.OfType<IAttributeRoute>()) {
    if (!string.IsNullOrWhiteSpace(route.RouteName) && !json.ContainsKey(route.RouteName)) {
        json.Add(route.RouteName, "/" + route.Url);
    }
}
Run Code Online (Sandbox Code Playgroud)

然而,这很好:

foreach (var route in GlobalConfiguration.Configuration.Routes)
{
    if (route is IAttributeRoute) // uhhhh?
    {
        var r = route as IAttributeRoute;
        if (!string.IsNullOrWhiteSpace(r.RouteName) && !json.ContainsKey(r.RouteName))
        {
            json.Add(r.RouteName, "/" + r.Url);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我发誓我不是在撒谎,它只适用于后一种代码.就像我说的那样,在正常的路线收集上这样做很好.正常的路由集合有其他类型的,不只是IAttributeRoute,但HttpRouteCollection 具有IAttributeRoute在其当前状态(在未来也可能有不同类型的路由).这可能是一个因素吗?

我错过了什么或者没有OfType做我在内部做的事情吗?

小智 2

我猜想这是 HostedHttpRouteCollection 处理对其内部集合的引用的方式的问题。GetEnumerator 仅返回 HttpWebRoute 类型的路由:

public override IEnumerator<IHttpRoute> GetEnumerator()
{
    return (
        from httpWebRoute in this._routeCollection.OfType<HttpWebRoute>()
        select httpWebRoute.HttpRoute).GetEnumerator();
}
Run Code Online (Sandbox Code Playgroud)

因此,虽然它使用 RouteTable.Routes 中的所有路由进行初始化,但它不会将它们全部作为 IEnumerable 返回。

既然如此,我想知道当您在第二个示例中说“它有效”时,这是否意味着它实际上会迭代您期望的所有项目?查看实现并运行与您发布的内容等效的内容,我认为不会。