论坛首页 入门技术论坛

C#几个不常用的关键字

浏览 3600 次
该帖已经被评为新手帖
作者 正文
   发表时间:2009-12-16   最后修改:2009-12-16
1、yield
yield关键字会告诉编译器当前的函数是在一个循环内部,编译器会相应生成一个执行它在循环体内部所表示行为的类,yield和return关键字一起用于为枚举器对象提供返回值,比如说:在foreach内部的每一次循环内,yield关键字用于终止当前循环:
以下为MSDN示例代码http://msdn.microsoft.com/en-us/library/9k7k7cf0.aspx
using System.Collections; 
public classList 
  { 

      public static IEnumerable Power(int number, int exponent) 
       { 
           int counter = 0; 
           int result = 1; 
           while(counter++ < exponent) 
           { 
               result = result * number; 
               yield return result; 
           } 
       } 

       static void Main() 
       { 
          foreach (int i in Power(2, 8)) 
           { 
               Console.Write("{0} ", i); 
           } 
       } 
   } 



输出:
2
4
8
16
32
64
128
256

===================================
2、using
定义一个范围,在范围外的对象将会被回收:
public static List<updatetime_model> UpdateTime(string datetime)
        {
             SqlParameter[] par = new SqlParameter[] {
                new SqlParameter("@time",datetime)
            };
            List<updatetime_model> time = null;
            [color=red]using (SqlDataReader r = SqlHelper.ExecuteReader("UpdateDate_GetTime",par))
            {
                while (r.Read())
                {
                    if (time == null)
                    {
                        time = new List<updatetime_model>();
                    }
                    time.Add(ConvertTime(r));
                }

                if (r.NextResult() && r.Read())
                {
                    lastdt = r.GetString(0);                 
                }
            }[/color]
            return time;
        }



参考链接:http://hatim.indexdev.net/2009/12/08/10-not-so-well-known-keywords-in-c/
   发表时间:2009-12-17  
话说这俩关键字都挺常用的……取决于使用场景和使用者使用C#的程度。特别是如果代码里有很多需要用到除内存外的别的资源时,using语句是非常常用的。using只是调用Dispose方法而已,并不导致对象被“回收”。
yield也跟“循环”没啥直接关系。只不过大家经常用循环来遍历IEnumerable<T>所以看起来似乎跟循环有关系……|||

要说不常用的话,fixed、unsafe、extern之类的更不常用了 >_<
0 请登录后投票
   发表时间:2009-12-17  
C#最不常用关键字候选:stackalloc, volatile, sizeof
0 请登录后投票
   发表时间:2009-12-17   最后修改:2009-12-17
幸存者 写道
C#最不常用关键字候选:stackalloc, volatile, sizeof

volatile常用与否倒不一定……不过用的时候很可能代码有问题 =_=||||
unsafe、stackalloc、fixed、sizeof还有&、*、->都属于相似的“常用程度”了orz

P.S. stackalloc挺讨厌的……在VS里要打static总是被IntelliSense先忽悠到stackalloc上 T.T
0 请登录后投票
   发表时间:2009-12-18   最后修改:2009-12-18
呵呵,yield是迭代器。
0 请登录后投票
   发表时间:2009-12-19  
using可是常用关键字。
0 请登录后投票
   发表时间:2009-12-19  
确实有一些很少用到的关键字
0 请登录后投票
   发表时间:2009-12-24  
using还是常看到或用到的,对一些实现了IDisposable接口的类,yield对我来说的确用的比较少的...
0 请登录后投票
论坛首页 入门技术版

跳转论坛:
Global site tag (gtag.js) - Google Analytics