列表的Nicer语法<keyvaluepair <string,string>&gt;?</keyvaluepair <string,string>

时间:2013-06-09 07:47:21

标签: c# c#-4.0 c#-3.0 c#-2.0

我有一个方法:

public void MyMethod(params KeyValuePair<string, string>[] properties);

我调用的内容如下:

MyMethod(
    new KeyValuePair("Name","Jack"), 
    new KeyValuePair("City", "New York"), 
    new KeyValuePair("Gender", "Male"), 
);

我更喜欢使用更漂亮的语法来调用该方法,类似于:

MyMethod({"Name","Jack"}, {"City","New York"}, {"Gender","Male"});

我最接近的是使用更改方法签名来接受字典作为方法参数并调用:

MyMethod(new Dictionary<string,string>()
{
    {"Name", "Jack"},
    {"City", "New York"},
    {"Gender", "Male"},
};

还有其他选择吗?

2 个答案:

答案 0 :(得分:0)

你可以只接受字符串作为参数,然后动态填充字典,就像这样。

public void MyMethod(params string[] properties) 
{
    var pairs = new Dictionary<string, string>();

    for(int i = 0; i < properties.length - 1; i += 2) 
    {
        pairs.Add(properties[i], properties[i + 1]);
    }
}

MyMethod("Name", "Jack", "City", "New York", "Gender", "Male");

答案 1 :(得分:0)

另一个选择是使用二维数组

static void PrintArray(int[,] arr)

PrintArray(new int[,] { { 1, 2 }, { 3, 4 }, { 5, 6 }, { 7, 8 } });

但我更喜欢词典方法

相关问题