在C#中实现多个IEnumerables可以通过以下几种方式实现:
public static IEnumerable<int> GetNumbers()
{
yield return 1;
yield return 2;
yield return 3;
}
public static IEnumerable<string> GetStrings()
{
yield return "Hello";
yield return "World";
}
// 使用多个IEnumerables
public static IEnumerable<object> CombineEnumerables()
{
foreach (var number in GetNumbers())
{
yield return number;
}
foreach (var str in GetStrings())
{
yield return str;
}
}
var numbers = new List<int> { 1, 2, 3 };
var strings = new List<string> { "Hello", "World" };
var combined = numbers.Concat(strings);
public class CombinedEnumerable : IEnumerable<object>
{
private IEnumerable<int> numbers;
private IEnumerable<string> strings;
public CombinedEnumerable(IEnumerable<int> numbers, IEnumerable<string> strings)
{
this.numbers = numbers;
this.strings = strings;
}
public IEnumerator<object> GetEnumerator()
{
foreach (var number in numbers)
{
yield return number;
}
foreach (var str in strings)
{
yield return str;
}
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
// 使用自定义的CombinedEnumerable类
var numbers = new List<int> { 1, 2, 3 };
var strings = new List<string> { "Hello", "World" };
var combined = new CombinedEnumerable(numbers, strings);
以上是在C#中实现多个IEnumerables的几种方法,可以根据具体需求选择适合的方式来实现。
领取专属 10元无门槛券
手把手带您无忧上云