将ValueTuple转换为IEnumerable

编程入门 行业动态 更新时间:2024-10-27 00:32:03
本文介绍了将ValueTuple转换为IEnumerable的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

是否有更明智的方法来进行以下操作:

Is there a saner way to do the following:

public static class ValueTupleAdditions { public static IEnumerable<object> ToEnumerable<A, B>(this ValueTuple<A, B> tuple) { yield return tuple.Item1; yield return tuple.Item2; } public static IEnumerable<object> ToEnumerable<A, B, C>(this ValueTuple<A, B, C> tuple) { yield return tuple.Item1; yield return tuple.Item2; yield return tuple.Item3; } [etc] }

由于人们要求一个用例,因此您可以开始使用.

Since people are asking for a use case, here you go.

using Xunit; namespace Whatever { public class SomeTestClass { public static IEnumerable<(string, Expression<Func<string, string>>, string)> RawTestData() { yield return ("Hello", str => str.Substring(3), "lo"); yield return ("World", str => str.Substring(0, 4), "worl"); } public static IEnumerable<object[]> StringTestData() { return RawTestData().Select(vt => new object[] { vt.Item1, vt.Item2, vt.Item3 }); // would prefer to call RawTestData().Select(vt => vt.ToArray()) here, but it doesn't exist. } [Theory, MemberData(nameof(StringTestData))] public void RunStringTest(string input, Expression<Func<string, string>> func, string expectedOutput) { var output = func.Compile()(input); Assert.Equal(expectedOutput, output); } } }

推荐答案

一种方法是通过 ITuple界面.

One way to do this is via the ITuple interface.

public interface ITuple { int Length { get; } object this[int index] { get; } }

它仅在.NET Core 2.0,Mono 5.0和.NET Framework的下一版本中可用(未发行,遵循4.7). 它不能(也永远不会)通过ValueTuple软件包作为旧框架的附件提供.

It is only available in .NET Core 2.0, Mono 5.0 and the next version of .NET Framework (unreleased, following 4.7). It is not (and will never be) available as an add-on to older frameworks via the ValueTuple package.

此API专为C#编译器使用而设计,用于以后的模式研究.

This API is designed for usage by the C# compiler for future work on patterns.

更多推荐

将ValueTuple转换为IEnumerable

本文发布于:2023-11-05 19:25:04,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1561646.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:转换为   ValueTuple   IEnumerable

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!