
👨💻个人主页:@元宇宙-秩沅
👨💻 hallo 欢迎 点赞👍 收藏⭐ 留言📝 加关注✅!
👨💻 本文由 秩沅 原创
👨💻 收录于专栏:unityc#专题
⭐🅰️系统路线学习点击跳转⭐
-
⭐【Unityc#专题篇】之c#核心篇】
⭐【Unityc#专题篇】之c#基础篇】
⭐【Unity-c#专题篇】之c#入门篇)
⭐【Unityc#专题篇】—基础章题单实践练习
⭐【Unityc#专题篇】—核心章题单实践练习
⭐迭代器原理⭐
-
@[TOC]
🎶(==A==)自定义标准迭代器原理
步骤:
namespace _迭代器
{
class DDQ : IEnumerable, IEnumerator
{
int[] arrary;
int curionPosition ;
public DDQ()
{
arrary = new int[] { 1, 2, 3, 4, 5, 6 };
}
public IEnumerator GetEnumerator()
{
Reset();
return this;
}
//使用foreach的时候会自动调用 Current属性来返回值
public object Current
{
get
{
return arrary[curionPosition];
}
}
public bool MoveNext()
{
curionPosition++;
//当光标位置小于数组长度时返回true
return curionPosition < arrary .Length ;
}
//重置光标的作用
public void Reset()
{
curionPosition = -1;
}
}
class Program
{
static void Main(string[] args)
{
DDQ ddq = new DDQ();
foreach (int item in ddq)
{
Console.WriteLine(item);
}
}
}
}
---
## 🎶(==B==)<font color=green >yield return 语法糖实现</font>
---
+ **1.作用:**
将复杂逻辑简单化,增加可读性
+ **2.只需继承一个接口: IEnumerable**
(所以 yield return 和IEnumrable配套使用)
+ **直接省去了IEnumreable接口下的几个成员方法,一步到位**
```cpp
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _迭代器
{
class DDQ : IEnumerable
{
int[] arrary;
public DDQ()
{
arrary = new int[] { 1, 2, 3, 4, 5, 6 };
}
public IEnumerator GetEnumerator()
{
for (int i = 0; i < arrary.Length; i++)
{
yield return arrary[i]; //直接省去了IEnumreable接口下的几个成员方法,一步到位
}
}
}
class Program
{
static void Main(string[] args)
{
DDQ ddq = new DDQ();
foreach (int item in ddq)
{
Console.WriteLine(item);
}
}
}
}
🎶(==c==)思维导图总结

🎶(==D==)实践练习

- 实践经验:
所以如果要使自定义的类能够使用foreach遍历,就需要继承迭代器接口通过两个方法实现:
1.自定义迭代器实现
2.语法糖yeild return 实现
⭐🅰️系统路线学习点击跳转⭐
-
⭐【Unityc#专题篇】之c#核心篇】
⭐【Unityc#专题篇】之c#基础篇】
⭐【Unity-c#专题篇】之c#入门篇)
⭐【Unityc#专题篇】—基础章题单实践练习
⭐【Unityc#专题篇】—核心章题单实践练习
你们的点赞👍 收藏⭐ 留言📝 关注✅是我持续创作,输出优质内容的最大动力!、
