c#编码技巧(二):yield关键字的作用
using System;
using System.Collections.Generic;
namespace ConsoleTest
{
class Program
{
static void Main(string[] args)
{
List<Student> lists = new List<Student>()
{
new Student() { Name = "Ben", Age = 18 },
new Student() { Name = "Pony", Age = 22 }
};
IEnumerable<string> sayHello = SayHello(lists);
//遍历IEnumerable<string>
foreach (string item in sayHello)
{
Console.WriteLine(item);
}
Console.ReadKey();
}
//yield的作用,与IEnumerable结合使用
private static IEnumerable<string> SayHello(List<Student> students)
{
foreach (Student item in students)
{
yield return "Hi " + item.Name + ",your age = " + item.Age.ToString();
}
}
public class Student
{
public string Name { get; set; }
public int Age { get; set; }
public string Address { get; set; }
}
}
}
[点击并拖拽以移动]
输出:
Hi Ben,your age = 18
Hi Pony,your age = 22
当然,此为简单演示。实际使用中结合Task使用,真香。后续再表。
c#编码技巧(一):初始化与赋值