传递键/值匿名对象作为参数

wic*_*rqm 2 c# model-view-controller .net-4.0

在mvc我可以使用这样的结构

@Html.TextAreaFor(model => model.iEventSummary, new { @class = "test" })
Run Code Online (Sandbox Code Playgroud)

我试图将其重现new { @class = "test" }为参数但未成功

testFunction( new {key1="value1", key2="value2", key3="" })

public static string testFunction(dynamic dict)
{
    string ret = string.Empty;
    IDictionary<string, string> dictionary = dict;
    foreach (var item in dictionary)
    {
        ret += item.Key + item.Value;
    }
    return ret;
}
Run Code Online (Sandbox Code Playgroud)

如何声明方法变量?如果我想传递new {key1="value1", key2="value2", key3="" }参数.

Pav*_*shy 5

您可以使用RouteValueDictionary将匿名对象转换为IDictionary.将您的功能更改为:

public static string TestFunction(object obj)
{
    var dict = new RouteValueDictionary(obj);
    var ret = "";
    foreach (var item in dict)
    {
        ret += item.Key + item.Value.ToString();
    }
    return ret;
}
Run Code Online (Sandbox Code Playgroud)

你可以使用它:

TestFunction(new { key1="value1", key2="value2", key3="" });
Run Code Online (Sandbox Code Playgroud)