天天看點

10個鮮為人知的C#關鍵字

10 Not So Well Known Keywords in C#

Ok before the flaming start let me state this. These are known to most hardcore programmers and not knowing them doesn’t make you less of a programmer either.

That said these keywords can come in handy and allow for better code quality and readability. Enjoy!

The yield keyword signals to the compiler that the method in which it appears is an iterator block. The compiler generates a class to implement the behavior that is expressed in the iterator block. In the iterator block, the yield keyword is used together with

the return keyword to provide a value to the enumerator object. This is the value that is returned, for example, in each loop of a foreach statement. The yield keyword is also used with break to signal the end of iteration.

example:

  public classList 

  { 

       //using System.Collections; 

      public static IEnumerable Power(int number, int exponent) 

       { 

           int counter = 0; 

           int result = 1; 

           while(counter++ < exponent) 

           { 

               result = result * number; 

               yield returnresult; 

           } 

       }

       static void Main() 

           // Display powers of 2 up to the exponent 8: 

          foreach (int i inPower(2, 8)) 

               Console.Write("{0} ", i); 

       } 

   } 

   /* 

   Output: 

   2 4 8 16 32 64 128 256 

   */

<a target="_blank" href="http://11011.net/software/vspaste"></a>

Beginning in Visual C# 3.0, variables that are declared at method scope can have an implicit type var. An implicitly typed local variable is strongly typed just as if you had declared the type yourself, but the compiler determines the type.

An application running on version 2.0 can also use the var keyword in their code as long as it’s compiled with 3.0 or up and set to output to 2.0.

var i = 10; // implicitly typed

int i = 10; //explicitly typed

Defines a scope, outside of which an object or objects will be disposed.

using (C c = new C())

{

    c.UseLimitedResource();

}

The readonly keyword is a modifier that you can use on fields. When a field declaration includes a readonlymodifier, assignments to the fields introduced by the declaration can only occur as part of the declaration or in a

constructor in the same class.

The as operator is like a cast operation. However, if the conversion is not possible, as returns null instead of raising an exception. 

class Base

    { public override string ToString()

        {

            return "Base";

        }

    }

    class Derived : Base

    { }

    class Program

    {

        static void Main()

            Derived d = new Derived();

            Base b = d as Base;

            if (b != null)

            {

                Console.WriteLine(b.ToString());

            }

Checks if an object is compatible with a given type.

An is expression evaluates to true if the provided expression is non-null, and the provided object can be cast to the provided type without causing an exception to be thrown.

The is keyword causes a compile-time warning if the expression is known to always be true or to always be false, but typically evaluates type compatibility at run time.

The is operator cannot be overloaded.

class Class1{ }

classClass2{ }

classClass3: Class2{ }

classIsTest

   {

        static voidTest(objecto)

            Class1a;

            Class2b;

            if(o isClass1)

                Console.WriteLine("o is Class1");

                a = (Class1)o;

                // Do something with "a."

            }

            else if (o is Class2)

                Console.WriteLine("o is Class2");

                b = (Class2)o;

                // Do something with "b."

            else

            {

                Console.WriteLine("o is neither Class1 nor Class2.");

            Class1 c1 = new Class1();

            Class2 c2 = new Class2();

            Class3 c3 = new Class3();

            Test(c1);

            Test(c2);

            Test(c3);

            Test("a string");

    /*

    o is Class1

    o is Class2

    o is neither Class1 nor Class2.

    */

n generic classes and methods, one issue that arises is how to assign a default value to a parameterized type T when you do not know the following in advance:

Whether T will be a reference type or a value type.

If T is a value type, whether it will be a numeric value or a struct.

Given a variable t of a parameterized type T, the statement t = null is only valid if T is a reference type and t = 0 will only work for numeric value types but not for structs. The solution is to use the default keyword, which will return null for reference

types and zero for numeric value types. For structs, it will return each member of the struct initialized to zero or null depending on whether they are value or reference types. For nullable value types, default returns a System.Nullabe&lt;T&gt;, which is initialized

like any struct.

T temp = default(T);

The global contextual keyword, when it comes before the :: operator, refers to the global namespace, which is the default namespace for any C# program and is otherwise unnamed.

class TestClass : global::TestApp { }

The volatile keyword indicates that a field might be modified by multiple concurrently executing threads. Fields that are declared volatile are not subject to compiler optimizations that assume access by a single thread. This

ensures that the most up-to-date value is present in the field at all times.

It can sometimes be necessary to reference two versions of assemblies that have the same fully-qualified type names, for example when you need to use two or more versions of an assembly in the same application. By using an external assembly alias, the namespaces

from each assembly can be wrapped inside root-level namespaces named by the alias, allowing them to be used in the same file.

To reference two assemblies with the same fully-qualified type names, an alias must be specified on the command line, as follows:

/r:GridV1=grid.dll

/r:GridV2=grid20.dll

This creates the external aliases GridV1 and GridV2. To use these aliases from within a program, reference them using the extern keyword. For example:

extern alias GridV1;

extern alias GridV2;

Each extern alias declaration introduces an additional root-level namespace that parallels (but does not lie within) the global namespace. Thus types from each assembly can be referred to without ambiguity using their fully qualified name, rooted in the appropriate

namespace-alias

In the above example, GridV1::Grid would be the grid control from grid.dll, and GridV2::Grid would be the grid control from grid20.dll.

Hope this helps!

Hatim

在正式開始之前,我需要先聲明:這些關鍵字對于偏向底層的程式員更加耳熟能詳,對這些關鍵字不了解并不影響你作為一個合格的程式員。

  這意味着這些關鍵字會讓你在編寫程式時得到更好的代碼品質和可讀性

  yield

  yield關鍵字會告訴編譯器目前的函數是在一個循環内部,編譯器會相應生成一個執行它在循環體内部所表示行為的類,yield和return關鍵字一起用于為枚舉器對象提供傳回值,比如說:在foreach内部的每一次循環内,yield關鍵字用于終止目前循環:

<code>   public classList   {      //using System.Collections;     public static IEnumerable Power(int number, int exponent)      {        int counter = 0;        int result = 1;        while(counter++ &lt; exponent)        {          result = result * number;          yield return result;        }      }        static void Main()      {        // Display powers of 2 up to the exponent 8:       foreach (int i in Power(2, 8))        {          Console.Write("{0} ", i);        }      }    }    /*    Output:    2 4 8 16 32 64 128 256    */</code>

  MSDN連結:http://msdn.microsoft.com/en-us/library/9k7k7cf0.ASPx

  var

  自從C# 3.0開始,在函數作用局範圍内聲明的變量可以通過var關鍵字聲明成隐含類型,隐含類型是強類型,你需要自己聲明隐含類型本地變量,然後編譯器會幫你決定為某種強類型。

在2.0版本上跑的程式也可以使用var關鍵字,但是需要你的編譯器是3.0以上版本并且設定代碼輸出版本為2.0:

<code>var i = 10; // implicitly typed    int i = 10; //explicitly typed</code>

  using()

  定義一個範圍,在範圍外的對象将會被回收:

<code>using (C c = new C())    {      c.UseLimitedResource();    }</code>

  MSDN連結:http://msdn.microsoft.com/en-us/library/yh598w02%28VS.80%29.aspx

  readonly

  readonly關鍵字是一個可作用在變量域上的修飾符,當一個變量域被readonly修飾後,這個變量隻可在聲明或者目前變量所屬類的構造器内指派。

  MSDN連結:http://msdn.microsoft.com/en-us/library/acdd6hb7%28VS.80%29.aspx

  as

  as操作符很像一個類型轉換器,然和,當轉換無法發生時(譯者按:比如類型不比對),as會傳回null而不是抛出一個異常:

<code>class Class1{ }    classClass2{ }    classClass3: Class2{ }    classIsTest      {        static voidTest(objecto)        {          Class 1a;          Class 2b;          if(o isClass1)          {            Console.WriteLine("o is Class1");            a = (Class1)o;            // Do something with "a."          }          else if (o is Class2)          {            Console.WriteLine("o is Class2");            b = (Class2)o;            // Do something with "b."          }          else          {            Console.WriteLine("o is neither Class1 nor Class2.");          }        }        static void Main()        {          Class1 c1 = new Class1();          Class2 c2 = new Class2();          Class3 c3 = new Class3();          Test(c1);          Test(c2);          Test(c3);          Test("a string");        }      }      /*      Output:      o is Class1      o is Class2      o is Class2      o is neither Class1 nor Class2.      */</code>

  default

  在泛型類和泛型方法中産生的一個問題是,在預先未知以下情況時,如何将預設值配置設定給參數化類型 T:

  T 是引用類型還是值類型。

  如果 T 為值類型,則它是數值還是結構。

  給定參數化類型 T 的一個變量 t,隻有當 T 為引用類型時,語句 t = null 才有效;隻有當 T 為數值類型而不是結構時,語句 t = 0 才能正常使用。解決方案是使用 default 關鍵字,此關鍵字對于引用類型會傳回 null,對于數值類型會傳回零。對于結構,此關鍵字将傳回初始化為零或 null 的每個結構成員,具體取決于這些結構是值類型還是引用類型:

<code>T temp = default(T);</code>

  MSDN連結:http://msdn.microsoft.com/en-us/library/xwth0h0d.aspx

  global

<code>class TestClass : global::TestApp { }</code>

  MSDN連結:http://msdn.microsoft.com/en-us/library/cc713620.aspx

  volatile

  volatile 關鍵字表示字段可能被多個并發執行線程修改。聲明為volatile 的字段不受編譯器優化(假定由單個線程通路)的限制。這樣可以確定該字段在任何時間呈現的都是最新的值。

  MSDN連結:http://msdn.microsoft.com/en-us/library/x13ttww7%28VS.80%29.aspx

  extern alias

  有時可能有必要引用具有相同完全限定類型名的程式集的兩個版本,例如當需要在同一應用程式中使用程式集的兩個或更多的版本時。通過使用外部程式集别名,來自每個程式集的命名空間可以在由别名命名的根級别命名空間内包裝,進而可在同一檔案中使用。

  若要引用兩個具有相同完全限定類型名的程式集,必須在指令行上指定别名,如下所示:

  /r:GridV1=grid.dll

  /r:GridV2=grid20.dll

  這将建立外部别名 GridV1 和 GridV2。若要從程式中使用這些别名,請使用 extern 關鍵字引用它們。例如:

  extern alias GridV1;

  extern alias GridV2;

  每一個外部别名聲明都引入一個額外的根級别命名空間,它與全局命名空間平行,而不是在全局命名空間内。是以,來自每個程式集的類型就可以通過各自的、根源于适當的名空間别名的完全限定名來引用,而不會産生多義性。

  在上面的示例中,GridV1::Grid 是來自 grid.dll 的網格控件,而 GridV2::Grid 是來自 grid20.dll 的網格控件。

  MSDN連結:http://msdn.microsoft.com/en-us/library/ms173212%28VS.80%29.aspx