如何获取 ValueTuple 字段名称的编译器别名以进行反射

How can I get the compiler aliases of ValueTuple field names for reflection

ValueTuples 允许为其 public 字段(Item1Item2 等)使用编译器别名。例如:

    var tuple = (Name:"apple",Date:DateTime.Now);
    var nameFieldValue = tuple.Name;//"apple"
    //here tuple.Name is a compiler alias for tuple.Item1

有什么方法可以通过反射做同样的事情吗?

    var tuple = (Name:"apple",Date:DateTime.Now);
    var nameFieldValue = tuple.GetType().GetField(nameof(tuple.Name)).GetValue(tuple);//null reference exception (the field is null)

我知道我能做到:

    var tuple = (Name:"apple",Date:DateTime.Now);
    var nameFieldValue = tuple.GetType().GetField("Item1").GetValue(tuple);//"apple"

但我需要根据它们的编译器别名 (tuple.Name) 获取 public 字段,而不是实际的字段名称 (tuple.Item1)。

元组值名称是一种类似于局部变量的 C# 语言构造,在代码编译后不存在。

编译器将翻译:

var tuple = (Name:"apple",Date:DateTime.Now);
var nameFieldValue = tuple.Name;

至:

ValueTuple<string, DateTime> valueTuple = new ValueTuple<string, DateTime>("apple", DateTime.Now);
string item = valueTuple.Item1;

并且如果您将该元组分配给具有相同结构的另一个元组:

var tuple = (Name:"apple",Date:DateTime.Now);
(string foo, DateTime bar) otherTuple = tuple;

编译器只会生成此代码:

ValueTuple<string, DateTime> valueTuple = new ValueTuple<string, DateTime>("apple", DateTime.Now);
ValueTuple<string, DateTime> valueTuple2 = valueTuple;

自己试试 https://sharplab.io/