C# Unity 面向对象补全计划 之 索引器与迭代器
本文仅作学习笔记与交流,不作任何商业用途,作者能力有限,如有不足还请斧正
本篇有部分内容出自唐老狮,唐老师网站指路:全部 - 游习堂 - 唐老狮创立的游戏开发在线学习平台 - Powered By EduSoho
目录
1.索引器
2.迭代器
1.索引器
我的理解 索引器就是一个对象内数据结构的属性, 像普通属性一样是一个语法糖
可以让 对象 像数组一样访问 对象内的集合元素 看一下就知道怎么用了
来一个C#版本的看看语法
public class StudentList
{
private string[] students = new string[5];
// 定义索引器 其中index代表外界索引的标志 返回值则是你的数据结构的类型
public string this[int index]
{
get => students[index];
set => students[index] = value;
}
}
// 使用索引器
StudentList list = new StudentList();
list[0] = "Alice"; // 设置值
Console.WriteLine(list[0]); // 输出 "Alice"(获取值)
要知道索引器不仅可以封装对象数组 还可以封装List 字典等等
来一个Unity版本的:
C#下 泛型的 ,其实上面那个就是Unity 泛型的
public class CustomListWrapper<T>
{
private List<T> _items = new List<T>();
// 索引器
public T this[int index]
{
get => _items[index];
set => _items[index] = value;
}
// 添加元素的方法
public void Add(T item) => _items.Add(item);
}
// 使用
var listWrapper = new CustomListWrapper<string>();
listWrapper.Add("A");
listWrapper[0] = "B"; // 通过索引器修改值
Console.WriteLine(listWrapper[0]); // 输出 "B"
2.迭代器
允许对象支持 foreach
遍历 就已经实现了迭代器 作用为按需生成序列值(延迟执行),不需要知道其内部逻辑结构
foreach的本质就是利用迭代器做迭代 ,借用唐老狮笔记:
自己写迭代器 只需要注意三点:
1 继承IEnumerator(可选)
2 实现GetEnumerator(必须)
3 继承IEnumerator(必须)
其内部就是一个可移动的"光标",每次MoveNext以后返回为true就让currentIndex+=1
using System;
using System.Collections;
class MyCollection
{
private int[] data = { 1, 2, 3, 4, 5 };
public MyEnumerator GetEnumerator()
{
return new MyEnumerator(this);
}
public class MyEnumerator : IEnumerator
{
private MyCollection collection;
private int currentIndex = -1;
public MyEnumerator(MyCollection collection)
{
this.collection = collection;
}
public object Current
{
get
{
if (currentIndex < 0 || currentIndex >= collection.data.Length)
{
throw new InvalidOperationException();
}
return collection.data[currentIndex];
}
}
public bool MoveNext()
{
currentIndex++;
return currentIndex < collection.data.Length;
}
public void Reset()
{
currentIndex = -1;
}
public void Dispose()
{
// 在这里进行资源清理相关操作,比如关闭文件、释放连接等
// 对于简单示例这里可以不做具体操作
}
}
}
class Program
{
static void Main()
{
MyCollection myCollection = new MyCollection();
MyCollection.MyEnumerator enumerator = myCollection.GetEnumerator();
while (enumerator.MoveNext())
{
Console.WriteLine(enumerator.Current);
}
enumerator.Dispose();
}
}
使用yield return直接替代了IEnumerator中这几个方法
using System;
using System.Collections.Generic;
class MyEnumerable
{
private int[] data = { 1, 2, 3, 4, 5 };
public IEnumerable<int> GetEnumerator()
{
for (int i = 0; i < data.Length; i++)
{
yield return data[i];
}
}
}
class Program
{
static void Main()
{
MyEnumerable myEnumerable = new MyEnumerable();
foreach (int num in myEnumerable.GetEnumerator())
{
Console.WriteLine(num);
}
}
}
总体来说 是不需要自己实现但是需要知道的知识