现在的位置: 首页 > 综合 > 正文

C#关健字

2012年03月06日 ⁄ 综合 ⁄ 共 1177字 ⁄ 字号 评论关闭

==========================================================

yield关健字

 

 var q = GetNums(5);

  public static IEnumerable GetNums(int nums)
        {
            int result = 0;

            for (int i = 0; i < nums; i++)
            {
                result = i;
                yield return result;

            }
        }

结果输出0,1,2,3,4五个数

msdn

 

yield 关键字向编译器指示它所在的方法是迭代器块。 编译器生成一个类来实现迭代器块中表示的行为。 在迭代器块中,yield 关键字与 return 关键字结合使用,向枚举器对象提供值。 这是一个返回值,例如,在 foreach 语句的每一次循环中返回的值。 yield 关键字也可与 break 结合使用,表示迭代结束。 有关迭代器的更多信息,请参见迭代器(C# 编程指南) 下面的示例演示两种形式的 yield 语句。

yield return <expression>;
yield break;

============================================================

 ref键字

 static void Method(ref int i)
        {
            // Rest the mouse pointer over i to verify that it is an int.
            // The following statement would cause a compiler error if i
            // were boxed as an object.
            i = i + 44;
        }

        static void Main()
        {
            int val = 1;
            Method(ref val);
            Console.WriteLine(val);

            // Output: 45
        }

===================================================================================

out 键字

 

 

 

    static void Method(out int i)
    {
        i = 44;
    }
    static void Main()
    {
        int value;
        Method(out value);
        // value is now 44
    }

抱歉!评论已关闭.