软件编程
位置:首页>> 软件编程>> C#编程>> C# 9使用foreach扩展的示例详解

C# 9使用foreach扩展的示例详解

作者:Newbe36524  发布时间:2023-01-27 08:35:56 

标签:C#9,foreach,扩展

在 C# 9 中,foreach 循环可以使用扩展方法。在本文中,我们将通过例子回顾 C# 9 中如何扩展 foreach 循环。

代码演示

下面是一个对树形结构进行深度优先遍历的示例代码:

using System;
using System.Collections.Generic;

namespace Example
{
   class TreeNode
   {
       public int Value { get; set; }
       public List<TreeNode> Children { get; set; }

public TreeNode(int value)
       {
           Value = value;
           Children = new List<TreeNode>();
       }
   }

static class TreeExtensions
   {
       public static IEnumerable<TreeNode> DepthFirst(this TreeNode root)
       {
           yield return root;
           foreach (var child in root.Children.SelectMany(DepthFirst))
           {
               yield return child;
           }
       }
   }

class Program
   {
       static void Main(string[] args)
       {
           var root = new TreeNode(1);
           root.Children.Add(new TreeNode(2));
           root.Children.Add(new TreeNode(3));
           root.Children[0].Children.Add(new TreeNode(4));
           root.Children[0].Children.Add(new TreeNode(5));

foreach (var node in root.DepthFirst())
           {
               Console.WriteLine(node.Value);
           }
           // Outputs: 1 2 4 5 3
       }
   }
}

在这个示例代码中,我们在 TreeNode 类中定义了一个值属性和一个存储子节点的列表属性。我们还在 TreeExtensions 类中定义了一个 DepthFirst 扩展方法,该方法使用 yield return 语句来返回树形结构的深度优先遍历结果。

在 Main 方法中,我们创建了一个树形结构,然后使用 foreach 循环来遍历树形结构的深度优先遍历结果。

之所以使用扩展方法往往是因为,我们可以在不修改 TreeNode 类的情况下,为 TreeNode 类添加新的功能。

那么接下来我们希望在 C# 9 中默认为 TreeNode 类添加 DepthFirst 行为,这样我们就可以直接使用 foreach 循环来遍历树形结构的深度优先遍历结果了。

C# 9 中的 foreach 扩展

在 C# 9 中,我们可以使用 foreach 扩展来实现上面的需求。我们只需要在 TreeNode 类中添加一个 GetEnumerator 方法,该方法返回一个实现了 IEnumerable 接口的对象即可。

static class TreeExtensions
{
   public static IEnumerable<TreeNode> DepthFirst(this TreeNode root)
   {
       yield return root;
       foreach (var child in root.Children.SelectMany(DepthFirst))
       {
           yield return child;
       }
   }

public static IEnumerator<TreeNode> GetEnumerator(this TreeNode root)
   {
       return root.DepthFirst().GetEnumerator();
   }
}

在上面的代码中,我们在 TreeNode 类中添加了一个 GetEnumerator 方法,该方法返回一个实现了 IEnumerable 接口的对象。这个对象就是我们在 DepthFirst 方法中使用 yield return 语句返回的结果。

现在我们可以直接使用 foreach 循环来遍历树形结构的深度优先遍历结果了。

foreach (var node in root)
{
   Console.WriteLine(node.Value);
}

来源:https://www.cnblogs.com/newbe36524/p/17018770.html

0
投稿

猜你喜欢

手机版 软件编程 asp之家 www.aspxhome.com