使用元组作为多个对象的多重赋值

huangapple go评论50阅读模式
英文:

Using tuples as multiple assignings for different objects

问题

以下是翻译好的内容:

例如,我在同一上下文(代码块)中有多个对象:

Button button;
public string FormCaption { get; set; }
public List<int> myValues { get; set; }

并且我有一个方法,该方法返回所有这些对象的值:

(string ButtonName, string FormCaption, List<int> SomeValues) MyCoolMethod() {...}

不要问我为什么 - 这只是一个示例。如果我像下面这样赋值上述对象,我是否实际上在使用元组作为左操作数,还是只是一种语法糖用于赋值?

(button.Name, FormCaption, myValues) = MyCoolMethod();

相对于执行以下操作,您认为使用这种方式进行赋值有哪些缺点:

var result = MyCoolMethod();
button.Name = result.ButtonName;
FormCaption = result.FormCaption;
myValues  = result.SomeValues;

?我的意思不仅仅是可读性(也许在这个示例中不明显,但在某些实际情况下,这样做可能更具可读性和合适),而是从性能和内存消耗的角度看。

英文:

For example, I have several objects in the same context (code block):

Button button;
public string FormCaption { get; set; }
public List&lt;int&gt; myValues { get; set; }

And I have a method that returns vaues for all these objects

(string ButtonName, string FormCaption, List&lt;int&gt; SomeValues) MyCoolMethod() {...}

Don't ask me why - that is just an example. If I assign aforementioned objects like this below, am I actually using a tuple as the left operand, or is it just a syntactic sugar for assigning?

(button.Name, FormCaption, myValues) = MyCoolMethod();

What disadvantages do you see to make assignings like this instead of making it so:

var result = MyCoolMethod();
button.Name = result.ButtonName;
FormCaption = result.FormCaption;
myValues  = result.SomeValues;

? I mean not only readability (perhaps not in this example, but in some real case it can be more readable and suitable), but in terms of performance and memory consumption.

答案1

得分: 4

根据将标准化解构赋值的草案PR,它一个"元组表达式" - 但这并不意味着它创建了一个元组值。事实上,编译器不仅在不需要创建ValueTuple对象时进行重要的工作,比如在构造函数中的(this.x, this.y, this.z) = (x, y, z)赋值中,还在能够避免的情况下甚至避免要求ValueTuple 类型 可用。

英文:

> If I assign aforementioned objects like this below, am I actually using a tuple as the left operand, or is it just a syntactic sugar for assigning?

Well, according to the draft PR that will standardize deconstructing assignment it is a "tuple expression" - but that doesn't mean it creates a tuple value. (Even if it did, it would be a ValueTuple&lt;,,&gt; so wouldn't require any heap allocation.)

In fact, the compiler does significant work not only to avoid creating ValueTuple objects when they're not needed - e.g. in an assignment of (this.x, this.y, this.z) = (x, y, z) in a constructor - but it avoids even requiring the ValueTuple type to be available if it can avoid it.

huangapple
  • 本文由 发表于 2023年3月4日 00:18:49
  • 转载请务必保留本文链接:https://go.coder-hub.com/75629501.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定