zoukankan      html  css  js  c++  java
  • ylbtech-LanguageSamples-Yield

    ylbtech-Microsoft-CSharpSamples:ylbtech-LanguageSamples-Yield

     

    1.A,示例(Sample) 返回顶部

    “Yield”示例

    本示例演示如何创建一个列表类来实现 IEnumerableyield 关键字,以对列表的内容启用 foreach 迭代。此示例定义了两个属性,其中一个返回奇数,另一个返回偶数。

    安全说明

    提供此代码示例是为了阐释一个概念,它并不代表最安全的编码实践,因此不应在应用程序或网站中使用此代码示例。对于因将此代码示例用于其他用途而出现的偶然或必然的损害,Microsoft 不承担任何责任。

    在 Visual Studio 中生成并运行“Yield 代码”示例

    • 在“调试”菜单上,单击“开始执行(不调试)”。

    从命令行生成并运行“Yield 代码”示例

    1. 使用“更改目录(cd)”命令转到“Yield”目录。

    2. 键入以下命令:

      csc Yield.cs
      Yield
    1.B,示例代码(Sample Code)返回顶部

    1.B.1, Yield.cs

    // 版权所有(C) Microsoft Corporation。保留所有权利。
    // 此代码的发布遵从
    // Microsoft 公共许可(MS-PL,http://opensource.org/licenses/ms-pl.html)的条款。
    //
    //版权所有(C) Microsoft Corporation。保留所有权利。
    
    using System;
    using System.Collections.Generic;
    using System.Text;
    
    namespace Yield
    {
        class Yield
        {
            public static class NumberList
            {
                // 创建一个整数数组。
                public static int[] ints = { 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377 };
    
                // 定义一个仅返回偶数的属性。
                public static IEnumerable<int> GetEven()
                {
                    // 使用 yield 返回列表中的偶数。
                    foreach (int i in ints)
                        if (i % 2 == 0)
                            yield return i;
                }
    
                // 定义一个仅返回偶数的属性。
                public static IEnumerable<int> GetOdd()
                {
                    // 使用 yield 仅返回奇数。
                    foreach (int i in ints)
                        if (i % 2 == 1)
                            yield return i;
                }
            }
    
            static void Main(string[] args)
            {
    
                // 显示偶数。
                Console.WriteLine("Even numbers");
                foreach (int i in NumberList.GetEven())
                    Console.WriteLine(i);
    
                // 显示奇数。
                Console.WriteLine("Odd numbers");
                foreach (int i in NumberList.GetOdd())
                    Console.WriteLine(i);
            }
        }
    }
    View Code

    1.B.2,

    1.B.EXE,

    Even numbers
    2
    8
    34
    144
    Odd numbers
    1
    3
    5
    13
    21
    55
    89
    233
    377
    请按任意键继续. . .

    1.B,

    1.C,下载地址(Free Download)返回顶部
    warn 作者:ylbtech
    出处:http://ylbtech.cnblogs.com/
    本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
  • 相关阅读:
    计算器类(C++&JAVA——表达式转换、运算、模板公式)
    使用/\_ 打印正三角形 C/C++
    Triangle2D类(Java)
    让键盘输入不影响界面的动态效果(C++)
    Java 7.21 游戏:豆机(C++&Java)
    Java 7.35 游戏:猜字游戏(C++&Java)
    Java 8.9 游戏:井字游戏(C++&Java)
    JAVA 8.20 游戏:四子连(Java&C++)
    简易Java文本编译器(C++)
    PAT 1089 狼人杀-简单版(20 分)(代码+测试点分析)
  • 原文地址:https://www.cnblogs.com/ylbtech/p/4197424.html
Copyright © 2011-2022 走看看