中文字幕av专区_日韩电影在线播放_精品国产精品久久一区免费式_av在线免费观看网站

溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

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

發布時間:2020-04-08 06:57:15 來源:網絡 閱讀:591 作者:蓬萊仙羽 欄目:開發技術

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!

yield

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 inPower(2, 8)) 
           { 
               Console.Write("{0} ", i); 
           } 
       } 
   } 
   /* 
   Output: 
   2 4 8 16 32 64 128 256 
   */

  

msdn reference: http://msdn.microsoft.com/en-us/library/9k7k7cf0.aspx

var

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.

example:

var i = 10; // implicitly typed

int i = 10; //explicitly typed

msdn reference: http://msdn.microsoft.com/en-us/library/bb383973.aspx

using()

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

example:

using (C c = new C())

{

    c.UseLimitedResource();

}

 

msdn reference: http://msdn.microsoft.com/en-us/library/yh698w02%28VS.80%29.aspx

readonly

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.

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

as

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

example:

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());

            }

        }

    }

 

msdn reference: http://msdn.microsoft.com/en-us/library/cscsdfbt.aspx

is

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.

example:

class Class1{ }

classClass2{ }

classClass3Class2{ }

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.");

            }

        }

        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.

    */

msdn reference: http://msdn.microsoft.com/en-us/library/scekt9xw.aspx

default

 

  •  

    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<T>, which is initialized like any struct.

example:

T temp = default(T);

msdn reference: http://msdn.microsoft.com/en-us/library/xwth0h0d.aspx

global

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.

example:

class TestClass global::TestApp { }

msdn reference: http://msdn.microsoft.com/en-us/library/cc713620.aspx

volatile

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.

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

extern alias

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.

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

 

Hope this helps!

Hatim

 

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

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

  yield

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

   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 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 
  */

  MSDN鏈接:http://msdn.microsoft.com/en-us/library/9k7k7cf0.ASPx

  var

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

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

var i = 10; // implicitly typed 
 
int i = 10; //explicitly typed

  MSDN鏈接:http://msdn.microsoft.com/en-us/library/bb383973.ASPx

  using()

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

using (C c = new C()) 
 
{ 
 
  c.UseLimitedResource(); 
 
}

  MSDN鏈接:http://msdn.microsoft.com/en-us/library/yh698w02%28VS.80%29.aspx

  readonly

  readonly關鍵字是一個可作用在變量域上的修飾符,當一個變量域被readonly修飾后,這個變量只可在聲明或者當前變量所屬類的構造器內賦值。

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

  as

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

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. 
 
  */

MSDN鏈接:http://msdn.microsoft.com/en-us/library/scekt9xw.ASPx

  default

  在泛型類和泛型方法中產生的一個問題是,在預先未知以下情況時,如何將默認值分配給參數化類型 T:

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

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

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

T temp = default(T);

  MSDN鏈接:http://msdn.microsoft.com/en-us/library/xwth0h0d.aspx

  global

  在  ::運算符前面使用的 global 上下文關鍵字引用全局命名空間,該命名空間是任何 C# 程序的默認命名空間,未以其他方式命名。

class TestClass : global::TestApp { }

  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

向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI

清丰县| 五峰| 乌兰浩特市| 景泰县| 比如县| 兰坪| 阜南县| 潞城市| 刚察县| 双柏县| 贡山| 杨浦区| 林州市| 迁西县| 大荔县| 铅山县| 庄浪县| 常州市| 新乐市| 南康市| 萨嘎县| 射阳县| 余庆县| 沙湾县| 土默特左旗| 织金县| 丹凤县| 泽普县| 乌兰浩特市| 永修县| 樟树市| 芜湖市| 济南市| 芷江| 永顺县| 上蔡县| 盖州市| 紫阳县| 沾化县| 闸北区| 乌鲁木齐县|