yield return的用法简介

使用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;
        }

  

  

转载于:https://www.cnblogs.com/mawenzhu/p/4056889.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值