6

我想我可以利用新的 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}");
    }
}
4

1 回答 1

4

不,那是不可能的。您对所使用的变量名称一无所知。此类信息不会传递给被调用者。

你可以像这样实现你想要的:

private static void Test(params string[][] values)
{
    ...
}

public static void Main(string[] args)
{
    string myName = "John", myAge = "33", myAddress = "Melbourne";
    Test(new string[] { nameof(myName), myName });
}

或使用字典:

private static void Test(Dictionary<string, string> values)
{
    ...
}

public static void Main(string[] args)
{
    string myName = "John", myAge = "33", myAddress = "Melbourne";
    Test(new Dictionary<string, string> { { nameof(myName), myName }, { nameof(myAge), myAge} });
}

或使用dynamic

private static void Test(dynamic values)
{
    var dict = ((IDictionary<string, object>)values);
}

public static void Main(string[] args)
{
    dynamic values = new ExpandoObject();
    values.A = "a";
    Test(values);
}

另一种可能性是使用Expression,您将其传递给方法。在那里,您可以从表达式中提取变量名并为其值执行表达式。

于 2016-11-03T13:57:35.300 回答