c# 多重赋值

c# multi assignment(c# 多重赋值)

本文介绍了c# 多重赋值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

int a, b, n;
...
(a, b) = (2, 3);
// 'a' is now 2 and 'b' is now 3

这类事情在 C# 中会非常有帮助.在此示例中,a"和b"没有封装在一起,例如位置的 X 和 Y.这是否以某种形式存在?

This sort of thing would be really helpfull in C#. In this example 'a' and 'b' arn't encapsulated together such as the X and Y of a position might be. Does this exist in some form?

下面是一个不那么简单的例子.

Below is a less trivial example.

(a, b) = n == 4 ? (2, 3) : (3, n % 2 == 0 ? 1 : 2);

Adam Maras 在评论中表明:

Adam Maras shows in the comments that:

var result = n == 4 ? Tuple.Create(2, 3) : Tuple.Create(3, n % 2 == 0 ? 1 : 2);

上面例子的一些工作,但是他指出它创建了一个新的三元组,而不是改变指定的值.

Sort of works for the example above however as he then points out it creates a new truple instead of changing the specified values.

Eric Lippert 询问用例,因此可能:

Eric Lippert asks for use cases, therefore perhaps:

(a, b, c) = (c, a, b); // swap or reorder on one line
(x, y) = move((x, y), dist, heading);
byte (a, b, c, d, e) = (5, 4, 1, 3, 2);
graphics.(PreferredBackBufferWidth, PreferredBackBufferHeight) = 400;

notallama 也有用例,它们在下面的答案中.

notallama also has use cases, they are in his answer below.

推荐答案

我们考虑过支持元组的语法糖,但它并没有成为 C# 4.0 的标准.不太可能成为 C# 5.0 的标准;C# 5.0 团队正忙于让 async/await 正常工作.我们将在假设的未来版本的语言中考虑它.

We have considered supporting a syntactic sugar for tuples but it did not make the bar for C# 4.0. It is unlikely to make the bar for C# 5.0; the C# 5.0 team is pretty busy with getting async/await working right. We will consider it for hypothetical future versions of the language.

如果您有一个非常可靠且令人信服的用例,这将有助于我们优先考虑该功能.

If you have a really solid usage case that is compelling, that would help us prioritize the feature.

这篇关于c# 多重赋值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:c# 多重赋值

基础教程推荐