我想我可以利用新的 c# 6 运算符 nameof 从 params 数组隐式构建键/值字典。
例如,考虑以下方法调用:
string myName = "John", myAge = "33", myAddress = "Melbourne";
Test(myName, myAge, myAddress);
我不确定是否会有一个 Test 的实现能够从 params 数组中暗示元素的名称。
有没有一种方法可以做到这一点nameof
,而无需反射?
private static void Test(params string[] values)
{
List<string> keyValueList = new List<string>();
//for(int i = 0; i < values.Length; i++)
foreach(var p in values)
{
//"Key" is always "p", obviously
Console.WriteLine($"Key: {nameof(p)}, Value: {p}");
}
}