ES6Generator与C#迭代器 [操作系统入门]

编程

 ES6 Generator:

利用阮大神的书中描述的:

形式上,Generator 函数是一个普通函数,但是有两个特征。一是,function关键字与函数名之间有一个星号;二是,函数体内部使用yield表达式,定义不同的内部状态(yield在英语里的意思就是“产出”)。

其实简单来说就是通过各种状态,函数可以返回多个值,看完文章,我觉着以下这功能可能会用的比较多

function* objectEntries(obj) {

let propKeys = Reflect.ownKeys(obj);

for (let propKey of propKeys) {

yield [propKey, obj[propKey]];

}

}

let jane = { first: ‘Jane‘, last: ‘Doe‘ };

for (let [key, value] of objectEntries(jane)) {

console.log(`${key}: ${value}`);

}

// first: Jane

// last: Doe

上面代码中,对象jane原生不具备 Iterator 接口,无法用for...of遍历。这时,我们通过 Generator 函数objectEntries为它加上遍历器接口,就可以用for...of遍历了。加上遍历器接口的另一种写法是,将 Generator 函数加到对象的Symbol.iterator属性上面。

function* objectEntries() {

let propKeys = Object.keys(this);

for (let propKey of propKeys) {

yield [propKey, this[propKey]];

}

}

let jane = { first: ‘Jane‘, last: ‘Doe‘ };

jane[Symbol.iterator] = objectEntries;

for (let [key, value] of jane) {

console.log(`${key}: ${value}`);

}

// first: Jane

// last: Doe

 优雅的Generator异步应用模块:thunkify和co模块;

 

C# yield

跟ES6中的Generator有异曲同工之妙.可以参考微软官方文档.

https://docs.microsoft.com/zh-cn/dotnet/csharp/language-reference/keywords/yield

主要看例子吧,例子很明显也是可以使用迭代器的方式每次返回一个值,但最终可以返回多个值。

迭代器方法:

publicclass PowersOf2

{

staticvoid Main()

{

// Display powers of 2 up to the exponent of 8:

foreach (int i in Power(2, 8))

{

Console.Write("{0} ", i);

}

}

publicstatic System.Collections.Generic.IEnumerable<int> Power(int number, int exponent)

{

int result = 1;

for (int i = 0; i < exponent; i++)

{

result = result * number;

yieldreturn result;

}

}

// Output: 2 4 8 16 32 64 128 256

}

 

迭代器的get访问器

publicstaticclass GalaxyClass

{

publicstaticvoid ShowGalaxies()

{

var theGalaxies = new Galaxies();

foreach (Galaxy theGalaxy in theGalaxies.NextGalaxy)

{

Debug.WriteLine(theGalaxy.Name + "" + theGalaxy.MegaLightYears.ToString());

}

}

publicclass Galaxies

{

public System.Collections.Generic.IEnumerable<Galaxy> NextGalaxy

{

get

{

yieldreturnnew Galaxy { Name = "Tadpole", MegaLightYears = 400 };

yieldreturnnew Galaxy { Name = "Pinwheel", MegaLightYears = 25 };

yieldreturnnew Galaxy { Name = "Milky Way", MegaLightYears = 0 };

yieldreturnnew Galaxy { Name = "Andromeda", MegaLightYears = 3 };

}

}

}

publicclass Galaxy

{

public String Name { get; set; }

publicint MegaLightYears { get; set; }

}

}

 

ES6 Generator与C#迭代器

以上是 ES6Generator与C#迭代器 [操作系统入门] 的全部内容, 来源链接: utcz.com/z/518739.html

回到顶部