簡體   English   中英

從列表元素創建對象

[英]Create object from List elements

非常抱歉,標題可能不夠翔實,但我不知道該如何解釋我要在問題中嘗試做的事情。

因此,我有一個MVC應用程序,並且正在從Web.config的配置部分加載路由。

為了封裝配置元素中所需的所有信息,我創建了一個RouteModel。

IEnumerable<RouteModel> configuredRoutes = RoutingFacade.GetAllRoutes();

foreach(RouteModel route in configuredRoutes)
{
    routes.MapRoute(route.Name, route.Url,
                    new { controller = "Home", action = "Index", managers = route.Managers });
}

忽略那里的經理鑰匙。

到目前為止還不錯,但是我的問題是這個。
我的RouteModel具有Constraints屬性,該屬性返回具有該路由的所有已配置約束的List<ConstraintModel>
ConstraintModel只有兩個屬性, NameValue

如您所知, MapRoute方法采用一個附加的object參數作為約束,該對象的構造如下:

new { constraint1 = value1, constraint2 = value2, .. }

如何將List<ConstraintModel>變成類似的東西?

非常感謝您抽出寶貴的時間閱讀我的問題,非常感謝

如果查看RouteCollection類的方法,您會注意到這里有一個Add方法( MSDN文章在此處 )。

您可以做的是調用它(這就是MapRoute擴展方法最終完成的工作),並根據需要創建Route類的實例。

Dictionary<string, object> constraints = new Dictionary<string, object>();
// populate your constraints into the constraints dictionary here..

Dictionary<string, object> dataTokens = new Dictionary<string, object>();
Dictionary<string, object> defaults = new Dictionary<string, object>();

Route route = new Route(" << url >> ", new MvcRouteHandler())
{
    Constraints = new RouteValueDictionary(constraints),
    DataTokens = new RouteValueDictionary(),
    Defaults = new RouteValueDictionary()
};

routes.Add(route);

這樣,您就有機會為約束指定string - object對。

編輯

此外,如果您對如何使用此方法有任何疑問,但對MapRoute擴展方法有什么了解,我建議您使用ILSpy來反匯編定義MapRoute的程序集(即System.Web.Mvc.dll ),然后轉到一步一步地發現MapRouteRouteCollection.Add之間的連接。

編輯2-關於路線名稱

您還可以檢查重載RouteCollection.Add(string name, RouteBase item) 這是您可以指定路線名稱的一種方式。

所以基本上您可以執行以下操作:

routes.Add(" My route with dynamically loaded constraints ", route);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM