C#实现自定义类的迭代
假设有两个类,一个学生类Student,它用来存储一个学生的信息,如名字和年龄。第二个是学校类School,它是学生类的集合。接下来我们一点点的看可迭代对象是如何进化的
一、石器时代的写法
using System;
using System.Collections.Generic;
using System.Linq;
namespace ConsoleApp1
{
internal class Student
{
public string Name { get; set; }
public int Age { get; set; }
public Student(string name, int age)
{
Name = name;
Age = age;
}
}
internal class School
{
private readonly List<Student> _list = new List<Student>();
public int Count => _list.Count();
public Student this[int index] => _list[index];
public void Add(Student item)
{
_list.Add(item);
}
}
internal class Program
{
private static void Main(string[] args)
{
var school = new School();
// 添加3个学生
school.Add(new Student("ahri", 15));
school.Add(new Student("ashe", 20));
school.Add(new Student("annie", 25));
// 遍历学校输出所有学生信息
for (var i = 0; i < school.Count; i++)
{
var item = school[i];
Console.WriteLine($"{item.Name}\t{item.Age}");
}
Console.ReadLine();
}
}
}
通过for循环遍历是在任何编程语言的入门书籍中都会提到的方法,因为它最基础。
二、使用IEnumerable
现代编程语言中基本上都会提供类似foreach这样的关键字,它可以说是for的升级版本,它不需要你提供集合对象的元素数量就可以遍历。而第一种遍历方法的缺点是无法使用foreach关键字
看到提示,一个集合类想通过foreach来遍历就得提供GetEnumerator方法,而这个方法正是IEnumerable接口唯一的一个方法,我们只需要继承这个接口
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
namespace ConsoleApp1
{
internal class Student
{
public string Name { get; set; }
public int Age { get; set; }
public Student(string name, int age)
{
Name = name;
Age = age;
}
}
internal class School : IEnumerable
{
private readonly List<Student> _list = new List<Student>();
IEnumerator IEnumerable.GetEnumerator()
{
return new StudentEnumerator(_list);
}
public void Add(Student item)
{
_list.Add(item);
}
}
internal class StudentEnumerator : IEnumerator
{
private readonly List<Student> _list;
private int _index = -1;
public StudentEnumerator(List<Student> items)
{
_list = items;
}
public bool MoveNext()
{
var count = _list.Count();
if (_index < count)
{
_index++;
}
return _index < _list.Count();
}
public void Reset()
{
_index = -1;
}
public object Current => _list[_index];
}
internal class Program
{
private static void Main(string[] args)
{
var school = new School { new Student("ahri", 15), new Student("ashe", 20), new Student("annie", 25) };
foreach (var item in school)
{
var student = (Student)item;
Console.WriteLine($"{student.Name}\t{student.Age}");
}
Console.ReadLine();
}
}
}
怎么看上去代码越来越多了呢?是的,为了能用上foreach,结果还得多写一个StudentEnumerator类,它继承自IEnumerator,必须实现2个方法和1个属性,在foreach遍历时会调用MoveNext来得知遍历是否要结束了(内部通过索引来判断是否到列表末尾了),没遍历完的话则通过Current属性来获取元素。可以看出,遍历的核心实质上都是在StudentEnumerator这个类里面,反而School显得多余了,C#支持继承多接口,所以对于这个例子我们是可以将它们合并的
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
namespace ConsoleApp1
{
internal class Student
{
public string Name { get; set; }
public int Age { get; set; }
public Student(string name, int age)
{
Name = name;
Age = age;
}
}
internal class School : IEnumerable, IEnumerator
{
private readonly List<Student> _list = new List<Student>();
private int _index = -1;
IEnumerator IEnumerable.GetEnumerator()
{
return this;
}
public void Add(Student item)
{
_list.Add(item);
}
public bool MoveNext()
{
var count = _list.Count();
if (_index < count)
{
_index++;
}
return _index < _list.Count();
}
public void Reset()
{
_index = -1;
}
public object Current => _list[_index];
}
internal class Program
{
private static void Main(string[] args)
{
var school = new School { new Student("ahri", 15), new Student("ashe", 20), new Student("annie", 25) };
foreach (var item in school)
{
var student = (Student)item;
Console.WriteLine($"{student.Name}\t{student.Age}");
}
Console.ReadLine();
}
}
}
一般不推荐这样写,因为在GetEnumerator这里返回的是自身,意味着迭代器不是独立的,如果在foreach嵌套的情况下可能不是你想要的
foreach (var item in school)
{
var student = (Student)item;
Console.WriteLine($"Dep1:{student.Name}\t{student.Age}");
foreach (var item2 in school)
{
var student2 = (Student)item2;
Console.WriteLine($"Dep2:{student2.Name}\t{student2.Age}");
}
}
因为共享的是一个迭代器,所以外面的foreach只执行了一次
三、引入yield,抛弃IEnumerator
为了循环时方便一点,似乎在集合类内部需要更多处理,有些得不偿失的感觉。还好,C#没让我们失望,它提供了一个更现代的武器:yield
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
namespace ConsoleApp1
{
internal class Student
{
public string Name { get; set; }
public int Age { get; set; }
public Student(string name, int age)
{
Name = name;
Age = age;
}
}
internal class School : IEnumerable
{
private readonly List<Student> _list = new List<Student>();
IEnumerator IEnumerable.GetEnumerator()
{
foreach (var item in _list)
{
yield return item;
}
}
public void Add(Student item)
{
_list.Add(item);
}
}
internal class Program
{
private static void Main(string[] args)
{
var school = new School { new Student("ahri", 15), new Student("ashe", 20), new Student("annie", 25) };
foreach (var item in school)
{
var student = (Student)item;
Console.WriteLine($"{student.Name}\t{student.Age}");
}
Console.ReadLine();
}
}
}
通过yield return来一个个返回元素,就可以完全抛弃了StudentEnumerator类了。但请明白,yield只是语法糖,实际上在程序编译时C#会自动实现一个对应的Enumerator类来完成迭代工作,只不过我们看不到而已。
最后,在foreach循环中每次都要做一次强制转换也让人受不了!还好,IEnumerable支持泛型
using System;
using System.Collections;
using System.Collections.Generic;
namespace ConsoleApp1
{
internal class Student
{
public string Name { get; set; }
public int Age { get; set; }
public Student(string name, int age)
{
Name = name;
Age = age;
}
}
internal class School : IEnumerable<Student>
{
private readonly List<Student> _list = new List<Student>();
public void Add(Student item)
{
_list.Add(item);
}
public IEnumerator<Student> GetEnumerator()
{
foreach (var item in _list)
{
yield return item;
}
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
internal class Program
{
private static void Main(string[] args)
{
var school = new School { new Student("ahri", 15), new Student("ashe", 20), new Student("annie", 25) };
foreach (var student in school)
{
Console.WriteLine($"{student.Name}\t{student.Age}");
}
Console.ReadLine();
}
}
}
推荐阅读
-
C# Winfrom 实现天际线绘制直线功能的示例代码
-
C#知识库|如何拖动无边框 WinForm 表单的位置?-实现步骤
-
35 岁实现财务*,腾讯程序员手握2300万提前退休?-1000万房产、1000万腾讯股票、加上300万的现金,一共2300万的财产。有网友算了一笔账,假设1000万的房产用于自住,剩下1300万资产按照平均税后20-50万不等进行计算,大约花上26-60年左右的时间才能赚到这笔钱。也就是说,普通人可能奋斗一辈子,才能赚到这笔钱。在很多人还在为中年危机而惶惶不可终日的时候,有的人的35岁,就已经安全着陆,试问哪个打工人不羡慕?但问题是有这样财富积累必然有像样的实力做靠山。没有人可以不劳而获。 看到这里,肯定有人说,那么对于普通人来说,卷可能真就成了唯一的出路。但是卷也有轻松的卷,“偷懒”的卷法,对于程序员而言,刨除掉一时无法改掉的开会传统占用的大部分时间,如何把有限的时间和精力放在真正重要的架构设计、需求设计上,而不是重复的造*,编码、改bug、手动测试。因此在科技改变生活的今天,学会使用AI工具成为程序员们的必备技能。 以全栈式全自动的软件开发工具飞算SoFlu软件机器人为例,作为全球首款面向微服务架构设计和最佳实践的软件机器人,SoFlu软件机器人改变了原来手工编码的作业模式,通过可视化拖拽方式以及参数配置就能实现等同于编写复杂代码的业务逻辑,在设计业务逻辑时就完成了微服务应用开发,做到“业务即图,图即代码”,实现“软件开发,十倍提效”。 而作为飞算SoFlu软件机器人的一个重要组成部分,FuncGPT(慧函数)支持所有类型函数创建。通过自然语言描述Java函数需求,实时生成高质量、高可读性的Java函数代码。生成代码可直接复制到IDEA,或一键导入Java全自动开发工具函数库。 FuncGPT(慧函数)具有五大核心能力: ● 自然语言:通过自然语言即可生成函数,降低软件开发门槛。 ● 秒级函数开发:全自动秒级开发函数,秒级完成,效率千倍提升。 ● 一站式函数开发应用:函数生成即可直接应用,效率、安全有保障。 ● 质量可靠:生成的函数代码符合业界规范、具备良好的可读性,符合最优解。 ● 灵活生成:可以根据开发人员的具体需求生成并支持调整和修改。 以“将文件流转换为File对象”这个需求为例,以下是FuncGPT(慧函数)秒级生成的代码: / 类名:FileConverter // 函数名:convertStreamToFile // 函数功能:将文件流转换为File对象 // POM依赖包:无 import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; public class FileConverter { /** * 将文件流转换为File对象 * @param inputStream 文件流 * @param filePath 文件路径 * @param fileName 文件名 * @return 转换后的File对象 * @throws IOException 如果发生I/O异常 */ public static File convertStreamToFile(InputStream inputStream, String filePath, String fileName) throws IOException { File file = new File(filePath + File.separator + fileName); // 创建File对象 try (FileOutputStream outputStream = new FileOutputStream(file)) { // 创建文件输出流 byte buffer = new byte[1024]; int bytesRead; while ((bytesRead = inputStream.read(buffer)) != -1) { // 从文件流读取数据并写入文件 outputStream.write(buffer, 0, bytesRead); } } return file; // 返回转换后的File对象 } } // 函数示例 // 将文件流转换为File对象示例 // 入参:inputStream,文件流 // 入参:filePath,文件路径 // 入参:fileName,文件名 // 出参:file,转换后的File对象 // 调用示例: // InputStream inputStream = new FileInputStream("example.txt"); // String filePath = "C:\\Users\\User\\Documents"; // String fileName = "example.txt"; // File file = FileConverter.convertStreamToFile(inputStream, filePath, fileName); // System.out.println(file.getAbsolutePath); // 输出结果:例如,将文件流转换为File对象后,文件的绝对路径为:C:\Users\User\Documents\example.txt // 则输出结果为:C:\Users\User\Documents\example.txt 通过分析,不难发现以上代码:
-
贪婪算法在 Python、JavaScript、Java、C++ 和 C# 中的多种实现及其在硬币变化、分数骑士、活动选择和使用哈夫曼编码的最小生成树问题中的应用实例
-
PHP 扩展类 ZipArchive 用于实现 Zip 文件的压缩和解压缩以及文件打包下载
-
使用 JWT、Interceptor 和 ThreadLocal 在任何位置获取令牌中的信息,并将其与自定义注解相结合,实现方法的身份验证。
-
一种结构设计模式,允许在对象中动态添加新行为。它通过创建一个封装器来实现这一目的,即把对象放入一个装饰器类中,然后把这个装饰器类放入另一个装饰器类中,以此类推,形成一个封装器链。这样,我们就可以在不改变原始对象的情况下动态添加新行为或修改原始行为。 在 Java 中,实现装饰器设计模式的步骤如下: 定义一个接口或抽象类作为被装饰对象的基类。 公共接口 Component { void operation; } } 在本例中,我们定义了一个名为 Component 的接口,该接口包含一个名为 operation 的抽象方法,该方法定义了被装饰对象的基本行为。 定义一个实现基类方法的具体装饰对象。 公共类 ConcreteComponent 实现 Component { public class ConcreteComponent implements Component { @Override public void operation { System.out.println("ConcreteComponent is doing something...") ; } } 定义一个抽象装饰器类,该类继承于基类,并将装饰对象作为一个属性。 公共抽象类装饰器实现组件 { protected Component 组件 public Decorator(Component component) { this.component = component; } } @Override public void operation { component.operation; } } } 在这个示例中,我们定义了一个名为 Decorator 的抽象类,它继承了 Component 接口,并将被装饰对象作为一个属性。在操作方法中,我们调用了被装饰对象上的同名方法。 定义一个具体的装饰器类,继承自抽象装饰器类并实现增强逻辑。 公共类 ConcreteDecoratorA extends Decorator { public ConcreteDecoratorA(Component 组件) { super(component); } } public void operation { super.operation System.out.println("ConcreteDecoratorA 正在添加新行为......") ; } } 在本例中,我们定义了一个名为 ConcreteDecoratorA 的具体装饰器类,它继承自装饰器抽象类,并实现了操作方法的增强逻辑。在操作方法中,我们首先调用被装饰对象上的同名方法,然后添加新行为。 使用装饰器增强被装饰对象。 公共类 Main { public static void main(String args) { Component 组件 = new ConcreteComponent; component = new ConcreteDecoratorA(component); 组件操作 } } 在这个示例中,我们首先创建了一个被装饰对象 ConcreteComponent,然后通过 ConcreteDecoratorA 类创建了一个装饰器,并将被装饰对象作为参数传递。最后,调用装饰器的操作方法,实现对被装饰对象的增强。 使用场景 在 Java 中,装饰器模式被广泛使用,尤其是在 I/O 中。Java 中的 I/O 库使用装饰器模式实现了不同数据流之间的转换和增强。 让我们打开文件 a.txt,从中读取数据。InputStream 是一个抽象类,FileInputStream 是专门用于读取文件流的子类。BufferedInputStream 是一个支持缓存的数据读取类,可以提高数据读取的效率,具体代码如下: @Test public void testIO throws Exception { InputStream inputStream = new FileInputStream("C:/bbb/a.txt"); // 实现包装 inputStream = new BufferedInputStream(inputStream); byte bytes = new byte[1024]; int len; while((len = inputStream.read(bytes)) != -1){ System.out.println(new String(bytes, 0, len)); } } } } 其中 BufferedInputStream 对读取数据进行了增强。 这样看来,装饰器设计模式和代理模式似乎有点相似,接下来让我们讨论一下它们之间的区别。 第三,与代理模式的区别: 代理模式的目的是控制对对象的访问,它在对象外部提供一个代理对象来控制对原对象的访问。代理对象和原始对象通常实现相同的接口或继承相同的类,以确保两者可以相互替换。 装饰器模式的目的是动态增强对象的功能,而这是通过对象内部的包装器来实现的。在装饰器模式中,装饰器类和被装饰对象通常实现相同的接口或继承自相同的类,以确保两者可以相互替代。装饰器模式也被称为封装器模式。 在代理模式中,代理类附加了与原类无关的功能。
-
算法系列--Linux 下的共享内存函数,实现进程间通信并封装为一个类(I)--主要函数说明
-
C# 十进制保留 2 位有效十进制的实现方法
-
Android 自定义控件,用于实现带有数值和动画的圆形进度条