如果您坚持将方法输入缩短到极致,我的想法与 Ethan Brown 相同。params
这是一个用于输入字典元素的小程序。
class Program
{
static void Main(string[] args)
{
MyMethod("Key1", 1, "Key2", 2, "Key3", 3);
}
static void MyMethod(params object[] alternatingKeysValues)
{
var dictionary = AlternatingKeysValuesToDictionary(alternatingKeysValues);
// etc...
}
static Dictionary<string, object> AlternatingKeysValuesToDictionary(params object[] alternatingKeysValues)
{
if (alternatingKeysValues.Count() % 2 == 1)
throw new ArgumentException("AlternatingKeysValues must contain an even number of items.");
return Enumerable
.Range(1, alternatingKeysValues.Count() / 2)
.ToDictionary(
i => (string)alternatingKeysValues.ElementAt(i * 2 - 2),
i => alternatingKeysValues.ElementAt(i));
}
}
也就是说,我认为像 Eric 的答案实际上更好。为非常冗长的内容分配捷径可以Dictionary<object, string>
让您非常接近您的理想,而不会牺牲清晰度或Dictionary
内置集合初始化程序提供的自然错误检查。
但是,我会寻求更清晰的措辞:
using Dict = System.Collections.Generic.Dictionary<string, object>;
用法:
MyMethod(new Dict {{string1, value1},{string2, value2}});
更好的是,替换Dict
为实际描述您的字典包含的内容,例如,fruitPrices 如果您的键是FruitName
并且您的值是Price
。