2

在 mvc 中,我可以使用这样的构造

@Html.TextAreaFor(model => model.iEventSummary, new { @class = "test" })

我正在尝试将此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;
}

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

4

2 回答 2

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;
}

你可以使用它:

TestFunction(new { key1="value1", key2="value2", key3="" });
于 2012-08-25T16:25:26.603 回答
3
public static string TestFunction(object obj)
{
    //To dictionary
    //var dict = obj.GetType().GetProperties()
    //                .ToDictionary(p=>p.Name,p=>p.GetValue(obj,null));

    //Directly ToString
    string result = String.Join(",", obj.GetType().GetProperties()
                                        .Select(p=>p.Name + ":" + p.GetValue(obj,null)));

    return result;
}
于 2012-08-25T16:33:08.180 回答