如何將包含在一個RouteCollection中的項目轉移到C#中的其他項目而無需使用foreach?如何克隆C#中的RouteCollection?
RouteCollection自Collection <繼承RouteBase>
如何將包含在一個RouteCollection中的項目轉移到C#中的其他項目而無需使用foreach?如何克隆C#中的RouteCollection?
RouteCollection自Collection <繼承RouteBase>
最後我提出:
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;
}
你可以試試:
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);
}
}
爲什麼約束避免foreach?考慮到.Select(),下面幾乎都做了同樣的事情並被接受。 – Cornelius