简体   繁体   中英

Possible create named tuple type using reflection?

I can create a normal tuple type with Tuple.Create or typeof(Tuple<,>).MakeGenericType etc, but how can I make a named tuple? With other property names than Item1 , Item2 etc, using reflection in runtime.

No, you can't, because named tuples are largely just syntatic sugar.

If you consider this code:

private void button1_Click(object sender, EventArgs e)
{
    var abc = Get();
    MessageBox.Show(string.Format("{0}: {1}", abc.name, abc.age));  
}

private (string name, int age) Get()
{
    return ("John", 30);
}

and then look at the decompiled code (I used JetBrains' dotPeek):

private void button1_Click(object sender, EventArgs e)
{
  ValueTuple<string, int> valueTuple = this.Get();
  int num = (int) MessageBox.Show(string.Format("{0}: {1}", (object) valueTuple.Item1, (object) (int) valueTuple.Item2));
}

[return: TupleElementNames(new string[] {"name", "age"})]
private ValueTuple<string, int> Get()
{
  return new ValueTuple<string, int>("John", 30);
}

You can see that, even though the MessageBox code uses the names, it's actually converted to .Item1 and .Item2 when it's compiled. Therefore, you should just use the ValueType constructor.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM