2

在 C# 9 中使用 foreach 扩展

 1 year ago
source link: https://www.newbe.pro/ChatAI/0x013-Extension-foreach-in-csharp-9/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

在 C# 9 中使用 foreach 扩展

2023-01-01 3

在 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);
}

在 C# 9 中,我们可以使用 foreach 扩展来为类添加新的行为。在上面的示例代码中,我们为 TreeNode 类添加了 DepthFirst 行为,这样我们就可以直接使用 foreach 循环来遍历树形结构的深度优先遍历结果了。

本文采用 Chat OpenAI 辅助注水浇筑而成,如有雷同,完全有可能。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK