次のようなパラメーターとして辞書を取るメソッドがあります。
void Do(Dictionary<string,string> d)
次のように、辞書コレクション初期化子と同じように呼び出すことができるメソッドを作成したいと思います。
Do({"sadfs","sdfsa"}, {"sadda","sada"}, ...);
誰もこれを行う方法を知っていますか?
できません-コレクション初期化子を使用できますが、タイプを指定する必要があります。
Do(new Dictionary<string, string> { {"x", "y"}, {"a", "b" } });
辞書が毎回同じになり、メソッドがそれを変更しないことがわかっている場合は、それを静的な読み取り専用変数に抽出します。これには、意味のある名前を付けることができるという利点があります。
このようにメソッドを定義するだけです
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");
}