初始化ViewDataDictionary

时间:2015-12-09 13:17:04

标签: c# .net asp.net-mvc-4

我需要构建一个接受参数并将其传递给System.Web.Mvc.ViewDataDictionary构造函数的函数。这是我的代码:

// this WORKS, but need to pass as parameter
var dic1 = new System.Web.Mvc.ViewDataDictionary { { "key", "value" } };

// this DOES NOT WORK
Test({ "key", "value" }); // I try do not have 'new Something({"", ""})'

function Test(object myParam) {
    var dic2 = new System.Web.Mvc.ViewDataDictionary { myParam };
    //...
}

有没有办法像我一样传递参数,而不需要传递整个
new System.Web.Mvc.ViewDataDictionary { { "key", "value" } }作为Test函数的参数?

PS。这是一些解释问题的测试代码

// WORKS
var dic1 = new System.Web.Mvc.ViewDataDictionary { { "key", "value" } };

// DOES NOT WORK

// A CASE
string[] myArr = { "key", "value" }; // OK
var dic2 = new System.Web.Mvc.ViewDataDictionary { myArr }; // NOK

// B CASE    
KeyValuePair<string, object> myPair = {"key", "value"}; // NOK
var dic3 = new System.Web.Mvc.ViewDataDictionary { myPair }; // OK

PPS 即可。多个参数案例:

// WORKS
var dic1 = new ViewDataDictionary { { "key", "value" }, {"key2", "value2"} };
var dic2 = new ViewDataDictionary { (replace w/ one single obj/arr impossible?)};

1 个答案:

答案 0 :(得分:2)

不幸的是,由于大括号只能用于collection initialization,因此无法实现您想要的效果。仅当解析器连接到new关键字时,解析器才会以特殊方式处理这些大括号。它解析它们并生成一堆Add个调用。

如果您只想传递密钥和值,可以这样做:

Test("key", "value"); 

void Test(string key, object value) {
    var dic2 = new ViewDataDictionary { { key, value  } };
    //...
}

ViewDataDictionary包含一个接受另一个ViewDataDictionary的构造函数:

Test(new ViewDataDictionary { { key, value  } }); 

void Test(ViewDataDictionary dictionary) {
     var dic2 = new ViewDataDictionary(dictionary);
     //...
}

如果您需要从一个ViewDataDictionary添加一些值到另一个ViewDataDictionary,您可以使用以下代码:

Test(new ViewDataDictionary { { key, value  } }); 

void Test(ViewDataDictionary dictionary) {
     var dic2 = new ViewDataDictionary();
     // ... initialize dic2
     foreach (var pair in dictionary)
     {
            dic2.Add(pair);
     }
}

如果需要传递一个数组(KeyValuePair元素)来初始化字典,可以这样做:

Test(new[] { new KeyValuePair<string, object>("key1", "value1"),
             new KeyValuePair<string, object>("key2", "value2") }); 

void Test(KeyValuePair<string, object>[] pairs) {
     var dic2 = new ViewDataDictionary();
     foreach (var pair in pairs)
     {
            dic2.Add(pair);
     }
     //...
}