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

C# 将键/值匿名对象作为参数传递,c#,model-view-controller,.net-4.0,C#,Model View Controller,.net 4.0,在mvc中,我可以使用这样的构造 @Html.TextAreaFor(model => model.iEventSummary, new { @class = "test" }) 我试图将这个新的{@class=“test”}复制为参数,但没有成功 testFunction( new {key1="value1", key2="value2", key3="" }) public static string testFunction(dynamic dict) { string

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

@Html.TextAreaFor(model => model.iEventSummary, new { @class = "test" })
我试图将这个
新的{@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;
}
testFunction(新的{key1=“value1”,key2=“value2”,key3=”“})
公共静态字符串测试函数(动态dict)
{
string ret=string.Empty;
词典=dict;
foreach(字典中的变量项)
{
ret+=item.Key+item.Value;
}
返回ret;
}
方法变量必须如何声明?
如果我想将
new{key1=“value1”,key2=“value2”,key3=“”}
作为参数传递。

您可以使用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="" });

是的,我可以做到这一点——但问题是我想在一行中做到这一点,而不需要像在htmlhelper-testFunction(new{key1=“value1”,key2=“value2”,key3=”“})中那样声明任何东西,然后移动var dict=new RouteValueDictionary(obj);在函数内部,并使函数参数类型-ObjectLookIn,从.NET 4开始提供。这些允许您对对象进行分组。您可以从标题中删除“(动态)”,因为它可能会产生误导,匿名对象没有动态性,只有编译器生成的类型。
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;
}