如何正确地将名称分配给列表中的命名元组

How do I correctly assign names to a named tuple in a list

我有以下代码,它似乎工作正常,但是当我检查列表中的元组时,它们被命名为 Item1、Item2、Item3,而不是我分配给它们的名称。我究竟做错了什么? (代码引用System.ValueTuple。)

感谢您的帮助。

var listContent = new List<(string date, double value, DateTime datetime)>();

// Read the file just created and put values in list of tuples
using (var reader = new StreamReader(rawFileName))
{
   while (!reader.EndOfStream)
   {
      var line = reader.ReadLine();
      var values = line.Split(',');
      listContent.Add((date: values[0],
         value: Convert.ToDouble(values[2]),
         datetime: DateTime.ParseExact(values[0], "yyyy-MM-dd", null)));
    }
}

如果我在上面的代码后面打个断点,在Immediate Window我可以做下面的事情,这就更令人费解了:

listContent[0]
("2017-01-01", 17.193, {01/01/2017 00:00:00})
    date: "2017-01-01"
    value: 17.193
    datetime: {01/01/2017 00:00:00}
    Raw View: ("2017-01-01", 17.193, {01/01/2017 00:00:00})
listContent[0].Item1
null
listContent[0].date
null
listContent[0].dummy
error CS1061: '(string date, double value, DateTime datetime)' does not contain a definition for 'dummy' and no accessible extension method 'dummy' accepting a first argument of type '(string date, double value, DateTime datetime)' could be found (are you missing a using directive or an assembly reference?)

[更新]

我已经超级简化了代码:

var listContent = new List<(string str1, string str2)>();
for (var n = 1; n < 100; n++)
{
   var tpl = (str1: "hello" + n.ToString(), str2: "world" + n.ToString());
   listContent.Add(tpl);
}
var z = listContent[0].str1;

并查看直接 window 给我的内容:

z
"hello1"
listContent[0].str1
null

所以我不会发疯:元组分配正确但出于某些奇怪的原因,直接 window 仍然给我 null for listContent[0].str1 ???

元组元素名称不是类型的一部分。编译器将名称转换为关联的 ItemN 属性.

除了局部变量(不能对其应用属性)外,名称在 [TupleElementNames] 属性中传达。例如,如果您要将 listContents 声明为一个字段,它将应用以下属性:

[TupleElementNames(new string[] { "date", "value", "datetime" })]

当您将鼠标光标悬停在 listContents 上时,调试器只会看到列表实例和其中的元组实例。给定一个实例,元组元素名称不可用。您将需要随附的 PropertyInfoFieldInfoParameterInfo,以便您可以获得传达名称的 TupleElementNamesAttribute。但是,如果您将其设为字段,调试器仍然只会查看实例。

我无法解释 Immediate window 中的行为,而 Watch window 似乎也有同样的问题。看起来您在 Visual Studio.

中发现了错误