1

如何在不使用 foreach 的情况下将一个 RouteCollection 中包含的项目转移到 C# 中的另一个?

RouteCollection 继承自 Collection< RouteBase >

4

3 回答 3

2

您可以使用CopyTo函数将整个集合复制到兼容的一维数组,

此方法使用 Array.Copy 复制元素。

http://msdn.microsoft.com/en-us/library/ms132408.aspx

于 2012-08-30T13:05:53.330 回答
1

最后我做了:

List<RouteBase> originalRoutes = routes.Select(i => i.Clone()).ToList();

为此,我需要两种扩展方法:

public static RouteBase Clone(this RouteBase route)
    {
        if (route.GetType() == typeof(Route))
            return ((Route)route).Clone();
        else
            return null;
    }

    public static Route Clone(this Route route)
    {
        Route cloneRoute = new Route(route.Url, route.RouteHandler);
        cloneRoute.Defaults = route.Defaults;
        cloneRoute.Constraints = route.Constraints;

        return cloneRoute;
    }
于 2012-09-05T08:53:23.703 回答
0

你可以试试:

static void Copy(RouteCollection source, RouteCollection dest)
    {
        Dictionary<string, RouteBase> _namedMap = typeof(RouteCollection).GetField("_namedMap", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance).GetValue(source) as Dictionary<string, RouteBase>;

        for (int i = 0; i < source.Count; i++)
        {
            var item = source[i];
            string name = _namedMap.Where(r => object.Equals(item, r.Value)).Select(r => r.Key).FirstOrDefault();
            dest.Add(name, item);
        }
    }
于 2016-04-06T09:09:57.087 回答