C#7是否具有数组/枚举解构? [英] Does C# 7 have array/enumerable destructuring?

查看:93
本文介绍了C#7是否具有数组/枚举解构?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Javascript ES6中,您可以像这样对数组进行解构:

In Javascript ES6, you are able to destructure arrays like this:

const [a,b,...rest] = someArray;

其中 a 是数组, b 是第二个, rest 是包含其余元素的数组。

where a is the first element in the array, b is the second, and rest is an array with the remaining elements.

我在C#7中知道可以在分配过程中对元组进行解构,但是找不到与解构数组/枚举有关的任何东西,例如:

I know in C#7 that you can destructure tuples during assignment, but could not find anything related to destructuring arrays/enumerables like this:

var (a,b) = someTuple;

我有一个 IEnumerable 第一个和第二个元素作为变量,而我需要其余的元素作为另一个IEnumerable。我有一个解决方案,但是觉得解构看起来会更干净。

I have an IEnumerable where I need the first and second elements as variables, and I need the rest of the elements as another IEnumerable. I have a solution, but feel that destructuring will look cleaner.

推荐答案

如果您想要一个与C#完全集成的解决方案语言功能,请使用 Evk的答案,其中隐藏了一些实现细节。如果您不关心该问题,则可以使用其中一个答案。

If you want a solution that is fully integrated with the C# language features, use Evk's answer, which hides some of the implementation detail. If you don't care about that, you can use either of the answers.

据我所知没有。但是,制作类似的东西并不难。

To my knowledge there is not. However, it is not very hard to make something similar.

像这样的扩展方法呢?

public static class EX
{
    public static void Deconstruct<T>(this T[] items, out T t0)
    {
        t0 = items.Length > 0 ? items[0] : default(T);
    }

    public static void Deconstruct<T>(this T[] items, out T t0, out T t1)
    {
        t0 = items.Length > 0 ? items[0] : default(T);
        t1 = items.Length > 1 ? items[1] : default(T);
    }
}

您可以像这样使用它:

int[] items = { 1, 2 };

items.Deconstruct(out int t0);

缺点是,您需要为每条要返回的项目使用扩展方法。因此,如果您要返回多个变量,则此方法可能不太有用。

The drawback is that you need an extension method per number of items to return. So if you have more than a few variables to return, this method might not be very useful.

请注意,我没有检查长度和相关内容,但是您了解我猜想需要做什么。

Note that I left out checking the length, and related stuff, but you understand what needs to be done I guess.

这篇关于C#7是否具有数组/枚举解构?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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