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

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 继承IEnumeratble(可选)

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

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

 

相关文章:

  • Spring AI 1.0.0-M6 快速开始(一)
  • MySQL批量生成建表语句
  • 解决CentOS 8.5被恶意扫描的问题
  • 美国国家航空航天局(NASA)的PUNCH任务
  • 第十章,防火墙带宽管理
  • Flink深入浅出之02
  • 软件系统属性
  • Java集合面试篇
  • 视觉-语言模型-出发点CLIP--(精读论文)
  • *图论基础(5)
  • 计算机网络笔记(一)——1.1计算机网络在信息时代中的作用
  • 数据库复习(第五版)- 第十章 数据库恢复技术
  • 【JavaEE】阻塞队列
  • HarmonyOS Next~鸿蒙系统ArkCompiler跨平台编译技术的革新实践
  • Flask 打包为exe 文件
  • C# 实现鼠标轨迹录制与回放自动化功能(附源码)
  • linux修改不可用编辑的文件(修改权限失败)
  • linux指令学习--sudo apt-get install vim
  • 【单片机项目】电源如何扩展、电源模块、电池模块如何接线
  • Codepen和tailwindcss 进行UI布局展示
  • 大学2025丨北大教授陈平原:当卷不过AI时,何处是归途
  • 中国旅马大熊猫“福娃”和“凤仪”启程回国
  • 专利申请全球领先!去年我国卫星导航与位置服务产值超5700亿
  • 尹锡悦宣布退出国民力量党
  • 新闻1+1丨强对流天气频繁组团来袭,该如何更好应对?
  • 俄乌代表团抵达谈判会场