使用new创建时,命名ValueTuple属性 [英] Name ValueTuple properties when creating with new

查看:83
本文介绍了使用new创建时,命名ValueTuple属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道我可以隐式创建元组时命名参数:

I know I can name parameters when I create a tuple implicitly like:

var me = (age: 21, favoriteFood: "Custard");

在显式创建元组时是否可以命名参数?即,

Is it possible to name parameters when a tuple is created explicitly? i.e.

var me = new ValueTuple<int, string>(21, "Custard");


推荐答案

不,您不能。 ValueTuple 类型实际上独立于C#中的命名字段支持。后者的工作方式更像匿名类型的命名属性。也就是说,编译器将分析代码并根据您的声明和用法为适当的成员生成别名。编译器通过分配来学习字段名称。由于基本的构造函数语法不提供命名字段的机制,因此您不能使用它直接生成具有命名字段的元组。

No, you can't. The ValueTuple types are actually independent of the named field support in C#. The latter works more like named properties for anonymous types. That is, the compiler analyzes the code and generates aliases to the appropriate members according to your declarations and usages. It is through the assignment that the compiler learns the names of the fields. Since the basic constructor syntax doesn't provide a mechanism to name the fields, you can't use that to directly generate a tuple with named fields.

当然,您可以通过多种方式重新解释从构造函数语法返回的值,以将名称分配给该返回值。我假设您知道这种方法,并且正在寻找更直接的方法。

Of course, there are ways you can re-interpret the value returned from the constructor syntax, to assign names to that returned value. I'm assuming you're aware of that approach and are looking for something more direct.

作为重新解释我的意思的示例,您可以做这样的事情:

As an example of what I mean by "re-interpret", you could do something like this:

static (int value, string text) ConvertToNamed((int, string) t) => t;

然后将使用新变量命名字段:

then this would name the fields, in a new variable:

var t1 = new ValueTuple<int, string>(21, "hello");
var t2 = ConvertToNamed(t1);

变量 t1 停留在 Item1 Item2 。但是编译器会隐式生成变量 t2 的所需名称。

The variable t1 is stuck with Item1 and Item2. But the compiler will implicitly generate the desired names for the variable t2.

也许更好的例子是不需要其他方法:

Maybe a better example is one where you don't require the additional method:

(int value, string text) t = new ValueTuple<int, string>(21, "hello");

同样,您并没有真正在构造函数语法中命名字段,但是它们会由局部变量声明。

Again, you're not really naming the fields in the constructor syntax, but they are reinterpreted by the local variable declaration.

这可能不是一个严重的限制。在需要一个持久的,易于分配的名称的情况下,声明用户定义的类型可能比使用元组语法更好。您也可以为用户定义的类型编写解构函数,并且这样声明类型意味着在反射,动态等方面,名称是一等公民。

This is probably not a serious limitation. In a scenario where there's a desire to have a persistent, easily-assigned name, it's probably better to declare a user-defined type than to use the tuple syntax anyway. You can write deconstructors for user-defined types as well, and declaring types like that means the names are first-class citizens when it comes to reflection, dynamic, etc.

这篇关于使用new创建时,命名ValueTuple属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆