Initialize a ViewDataDictionary

本文关键字:ViewDataDictionary Initialize | 更新日期: 2023-09-27 18:26:12

我需要构建一个函数,该函数接受一个参数并将其传递给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?)};

Initialize a ViewDataDictionary

遗憾的是,由于花括号只能用于集合初始化,因此无法实现您想要的结果。只有当这些花括号连接到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);
     }
     //...
}
相关文章:
  • 没有找到相关文章