[英]How to pass dictionary items to a function in C#
我正在編寫一個自定義幫助程序來處理嵌套的導航菜單。 我在將一組數組(或字典)傳遞給函數時遇到了一些麻煩。
以下是Razor對ActionMenuItem的調用
@Html.ActionMenuItem("All Reports", "index", "report", "icon-bar-chart", "last", new {"title" = "Report 1", "action" = "report1"}, new {"title" = "Report 2", "action" = "report2"})
public static MvcHtmlString ActionMenuItem(this HtmlHelper htmlHelper, String linkText, String actionName, String controllerName, String iconType = null, string classCustom = null, params Dictionary<string, string> subMenu)
我的功能運行良好,直到字典項為止。 我能夠生成一個單級菜單,但嘗試使其與嵌套菜單一起使用。
任何幫助和教訓,我們將不勝感激!
謝謝,
RD
你能做這樣的事情:
public static MvcHtmlString ActionMenuItem(
this HtmlHelper htmlHelper,
String linkText,
String actionName,
String controllerName,
String iconType = null,
string classCustom = null,
params KeyValuePair<string, string>[] subMenus)
{ ... }
var dict = new Dictionary<string, string>()
{
{ "a", "b" },
{ "c", "d" },
};
*.ActionMenuItem(*, *, *, *, *, dict.ToArray());
您不能使用params
關鍵字將Dictionary<TKey, TValue>
聲明為參數數組。
根據c#規范:
用
params
修飾符聲明的params
是參數數組。 如果形式參數列表包含參數數組,則它必須是列表中的最后一個參數,並且必須是一維數組類型 。
Dictionary
不是一維數組 。
您可以創建一個具有兩個屬性的類: Title
和Action
,並將參數類型更改為MyClass[]
而不是字典。
嘗試這樣的事情:
@Html.ActionMenuItem(
"All Reports",
"index",
"report",
"icon-bar-chart",
"last",
new Dictionary<string, string>[]
{
new Dictionary<string, string>()
{
{ "title", "Report 1" },
{ "action", "report1" }
},
new Dictionary<string, string>()
{
{ "title", "Report 2" },
{ "action", "report2" }
}
} )
public static MvcHtmlString ActionMenuItem(
this HtmlHelper htmlHelper,
string linkText,
string actionName,
string controllerName,
string iconType = null,
string classCustom = null,
params Dictionary<string, string>[] subMenu)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.