繁体   English   中英

如何在C#中将字典项传递给函数

[英]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不是一维数组

您可以创建一个具有两个属性的类: TitleAction ,并将参数类型更改为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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM