1. yield使用
using System;
using System.Collections.Generic;
namespace ConsoleApp5
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("GetEnumerator");
var names = new A();
foreach(var n in names)
{
Console.WriteLine(n);
}
Console.WriteLine("Reverse");
foreach (var n in names.Reverse())
{
Console.WriteLine(n);
}
Console.WriteLine("Subset");
foreach (var n in names.Subset(1, 2))
{
Console.WriteLine(n);
}
Console.ReadLine();
}
}
class A
{
string[] names = { "name1", "name2", "name3","name4" };
public IEnumerator<string> GetEnumerator()
{
for(int i = 0; i < 4; i++)
{
yield return names[i];
}
}
public IEnumerable<string> Reverse()
{
for(int i = 3; i >= 0; i --)
{
yield return names[i];
}
}
public IEnumerable<string> Subset(int index,int length)
{
for(int i = index; i < index+length; i++)
{
yield return names[i];
}
}
}
}
2.yiled 理解
2.1 代码
using System;
using System.Collections;
using System.Collections.Generic;
namespace ConsoleApp5
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("A.GetEnumerator");
var names = new A();
foreach(var n in names)
{
Console.WriteLine(n);
}
Console.WriteLine("B.GetEnumerator");
var namesb = new B();
foreach (var n in namesb)
{
Console.WriteLine(n);
}
Console.ReadLine();
}
}
class A
{
protected string[] names = { "name1", "name2", "name3","name4" };
public IEnumerator<string> GetEnumerator()
{
for(int i = 0; i < 4; i++)
{
yield return names[i];
}
}
}
class B
{
protected string[] names = { "name1", "name2", "name3", "name4" };
public IEnumerator<string> GetEnumerator()
{
return new Enumerator(-1, names);
}
public class Enumerator : IEnumerator<string>, IEnumerator, IDisposable
{
public Enumerator(int i, string[] s)
{
_current = i;
names = s;
}
string[] names;
int _current;
public string Current => names[_current];
object IEnumerator.Current => names[_current];
public void Dispose()
{
}
public bool MoveNext()
{
_current++;
if (_current < 4)
{
return true;
}
else
{
_current = 0;
return false;
}
}
public void Reset()
{
throw new NotImplementedException();
}
}
}
}
2.2 代码分析
3.学习笔记
关于yield的理解,起初挺抽象,但是后来换了一个方向,yield最终是要编译成其他形式的代码的,也就是说,这里不能用理解if、else、for 这些代码的理解方法来理解。于是想把yield的语句转换成更基础的代码,然后就豁然开朗了。
4. 英语
yield
v. 出产(产品或作物);产出(效果、收益等);生息;屈服;放弃;停止争论;给(车辆)让路;(在外力、重压等下)屈曲
n. 产量;利润,红利率