使用yield return 语句可一次返回一个元素。
迭代器的声明必须满足以下要求:
-
IEnumerator<T>。
yield return 语句中的表达式 类型隐式转换为泛型类型参数。
yield break 语句:
-
-
包含不安全的块的方法。
public class Student { public String Name { get; set; } public int Age { get; set; } //代码更简洁 public IEnumerable<Student> Students { get { yield return new Student { Name = "Tadpole", Age = 400 }; yield return new Student { Name = "Pinwheel", Age = 25 }; yield return new Student { Name = "Milky Way", Age = 0 }; yield return new Student { Name = "Andromeda", Age = 3 }; } } public IEnumerable<Student> Students2 { get { List<Student> list = new List<Student>(); list.Add(new Student { Name = "Tadpole", Age = 400 }); list.Add(new Student { Name = "Tadpole", Age = 400 }); list.Add(new Student { Name = "Tadpole", Age = 400 }); list.Add(new Student { Name = "Tadpole", Age = 400 }); list.Add(new Student { Name = "Tadpole", Age = 400 }); return list; } } }
//将不会返回空
public static IEnumerable<string> Test()
{
yield break;
}