3

次のようなパラメーターとして辞書を取るメソッドがあります。

void Do(Dictionary<string,string> d)

次のように、辞書コレクション初期化子と同じように呼び出すことができるメソッドを作成したいと思います。

Do({"sadfs","sdfsa"}, {"sadda","sada"}, ...);

誰もこれを行う方法を知っていますか?

4

2 に答える 2

5

できません-コレクション初期化子を使用できますがタイプを指定する必要があります。

Do(new Dictionary<string, string> { {"x", "y"}, {"a", "b" } });

辞書が毎回同じになり、メソッドがそれを変更しないことがわかっている場合は、それを静的な読み取り専用変数に抽出します。これには、意味のある名前を付けることができるという利点があります。

于 2012-09-04T13:32:21.697 に答える
0

このようにメソッドを定義するだけです

public static void TheMethod(IDictionary<string, string> d)
    {
        MessageBox.Show(d.Count);
        // Other processing
    }

このように呼んでください

public static void MyMethod(string s)
    {
        TheMethod("name, value");
    }

複数の引数を渡したい場合は、定義をに変更してください。

public static void TheMethod(ICollection<IDictionary<string, string>> d)
    {
        MessageBox.Show(d.Count);
        // Other processing
    }

public static void MyMethod(string s)
    {
        TheMethod("name, value", "otherName, otherValue");
    }
于 2012-09-04T13:44:41.007 に答える