首页 > 其他 > 详细

yield return的用法简介

时间:2014-10-28 17:21:30      阅读:214      评论:0      收藏:0      [点我收藏+]
使用yield return 语句可一次返回一个元素。

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

 返回 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的用法简介

原文:http://www.cnblogs.com/mawenzhu/p/4056889.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!