Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
257 views
in Technique[技术] by (71.8m points)

c# - Name ValueTuple properties when creating with new

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");
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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);

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...