简体   繁体   English

可能使用反射创建命名元组类型?

[英]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? 我可以使用Tuple.Createtypeof(Tuple<,>).MakeGenericType等创建普通的元组类型,但是如何创建命名的元组呢? With other property names than Item1 , Item2 etc, using reflection in runtime. 使用除Item1Item2等以外的其他属性名称,在运行时使用反射。

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): 然后查看反编译的代码(我使用了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. 您可以看到,即使MessageBox代码使用了名称,编译时实际上.Item2将其转换为.Item1.Item2 Therefore, you should just use the ValueType constructor. 因此,您应该只使用ValueType构造函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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