当前位置: 首页 > article >正文

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

         总体来说 是不需要自己实现但是需要知道的知识

 


http://www.kler.cn/a/573139.html

相关文章:

  • Go语言select的高级玩法
  • Vue的简单入门 三
  • OCPP扩展机制与自定义功能开发:协议灵活性设计与实践 - 慧知开源充电桩平台
  • 确定信号分析:从傅里叶级数到信号带宽的Matlab实践
  • Zookeeper 的 Node(Znode) 是什么?Zookeeper 监听机制的特点是什么?
  • Mybatis控制台打印SQL执行信息(执行方法、执行SQL、执行时间)
  • ShareExpert SparseMoE的学习
  • Sass 模块化革命:深入解析 @use 语法,打造高效 CSS 架构
  • 如何在 WebSocketHandler 中控制连接的断开
  • 016.3月夏令营:数理类
  • js 之 lodash函数库 的下载与基础使用
  • 深圳区域、人口、地铁线
  • Amorphous Data如何在DigitalOcean上构建智能、经济的AI Agent
  • Matlab实现车牌识别
  • 【AI神经网络与人脑神经系统的关联及借鉴分析】
  • 数据结构(四)栈和队列
  • python代码注释方式
  • (数据结构)双向链表
  • 自己的网页加一个搜索框,调用deepseek的API
  • 2025-03-04 学习记录--C/C++-PTA 习题5-3 使用函数计算两点间的距离