List<> 是否支持 C# 和 .NET Core 3 中带有字段名称的元组?

Does List<> support tuples with field names in C# and .NET Core 3?

我创建了一个包含命名字段的元组列表,如下所示:

var list = new List<(string First, string Last)>();
var lt = (First: "first", Last: "last");
list.Add(lt);

但是,当我在 VS2019 调试器中查看列表的内容时,我可以看到字段名称显示为“Item1”和“Item2”。

有没有办法让 List<> 保留元组字段名称?

List 支持命名元组; 调试器 就是问题所在。命名元组使用“编译器魔法”允许您在设计时引用自定义名称,但在编译时命名字段将转换为默认名称 ItemX:

来自MDSN

At compile time, the compiler replaces non-default field names with the corresponding default names. As a result, explicitly specified or inferred field names aren't available at run time.

在设计时从列表中提取项目后,您仍然可以引用名称

    var list = new List<(string First, string Last)>();
    var lt = (First: "first", Last: "last");
    list.Add(lt);

    Console.WriteLine(lt);  //  "(first, last)"

    var x = list[0]; 

    Console.WriteLine(x); // "(first, last)"

    // Can still reference the names of a tuple from the list at coding time
    Console.WriteLine(x.First);  // "first"
    Console.WriteLine(x.Item1);  // "first"

但在运行时(例如使用反射时)只有默认字段名称可用:

    foreach(var p in x.GetType().GetFields())
    {
        Console.WriteLine(p.Name);
    }
     
Item1
Item2

调试器可能可能获得design-time名称,但显然该功能尚未构建。