首页 > 代码库 > yield return的用法简介

yield return的用法简介

使用yield return 语句可一次返回一个元素。

   迭代器的声明必须满足以下要求:

  • 返回类型必须为 IEnumerable、IEnumerable<T>IEnumerator 或 IEnumerator<T>

 返回 IEnumerable 或 IEnumerator 的迭代器的 yield 类型为 object。如果迭代器返回 IEnumerable<T> 或 IEnumerator<T>,则必须将yield return 语句中的表达式    类型隐式转换为泛型类型参数。

   你不能在具有以下特点的方法中包含 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;        }

  

  

yield return的用法简介