9.IEnumerable可枚举接口 C#例子 WPF例子

cs 复制代码
        private async void Button_Click(object sender, RoutedEventArgs e)
        {

            // 调用时可以传入 List、Array、HashSet 等任何实现了 IEnumerable<string> 的集合
            List<string> myList = new List<string> { "A", "B" };
            ProcessItems(myList);

            string[] myArray = { "X", "Y" };
            ProcessItems(myArray);

        }

        public void ProcessItems(IEnumerable<string> items)
        {
            foreach (string item in items)
            {
                this.WriteLine(item);
            }
        }

代码介绍

这段代码展示了一个简单的事件处理程序和一个通用方法,用于处理实现了 IEnumerable<string> 接口的集合。

Button_Click 方法
  • 触发条件 :当按钮被点击时,Button_Click 方法会被触发。

  • 功能

    1. 创建一个 List<string> 集合 myList,并初始化为包含两个字符串 "A""B"

    2. 调用 ProcessItems 方法,传入 myList

    3. 创建一个字符串数组 myArray,并初始化为包含两个字符串 "X""Y"

    4. 再次调用 ProcessItems 方法,传入 myArray

ProcessItems 方法
  • 参数items 是一个实现了 IEnumerable<string> 接口的集合,可以是 List<string>string[] 或其他任何实现了该接口的集合类型。

  • 功能

    • 使用 foreach 循环遍历传入的集合 items

    • 对于集合中的每个字符串 item,调用 this.WriteLine(item) 方法将其输出。

特点
  • 通用性ProcessItems 方法可以处理任何实现了 IEnumerable<string> 接口的集合(如 List<string>string[]),展示了泛型接口的强大功能

这段代码演示了如何使用 IEnumerable<string> 接口来处理不同类型的数据集合,体现了泛型接口在提高代码复用性和灵活性方面的优势。

相关推荐
liliangcsdn1 天前
mstsc不在“C:\Windows\System32“下在C:\windows\WinSxS\anmd64xxx“问题分析
开发语言·windows
低频电磁之道1 天前
解决 Windows C++ DLL 导出类不可见的编译错误
c++·windows
jerryinwuhan1 天前
RDD第二次练习
开发语言·c#
Unity粉末状在校生1 天前
清除microsoft edge账户信息
前端·microsoft·edge
IDC02-阿杰1 天前
Windows WSL2安装Ubuntu24.04全攻略
linux·windows
专注VB编程开发20年1 天前
Windows11 ARM系统直接运行X86 exe,高通CPU同时运行安卓APP,任意软件
microsoft
aini_lovee1 天前
C# 快速搜索磁盘文件解决方案
开发语言·c#
勤自省1 天前
Windows 文件无法粘贴到 Linux(Ubuntu)系统的解决方案
linux·windows·ubuntu
张赐荣1 天前
为资源管理器文件右键菜单增加 使用 Web 搜索 功能
windows
以太浮标1 天前
华为eNSP模拟器综合实验之- DHCP、DNS、HTTP和FTP服务器配置案例Client-Server
linux·服务器·windows·http·华为·信息与通信