跳轉至內容

C# 程式設計/關鍵字

來自華夏公益教科書


C# 關鍵字
abstract as base bool break
byte case catch char checked
class const continue decimal default
delegate do double else enum
event explicit extern false finally
fixed float for foreach goto
if implicit in int interface
internal is lock long namespace
new null object operator out
override params private protected public
readonly ref return sbyte sealed
short sizeof stackalloc static string
struct switch this throw true
try typeof uint ulong unchecked
unsafe ushort using var virtual
void volatile while
特殊 C# 識別符號(上下文關鍵字)
add alias async await dynamic
get global nameof partial remove
set value when where yield
上下文關鍵字(用於查詢)
ascending by descending equals from
group in into join let
on orderby select where

抽象類除了已實現的成員外,還可以包含抽象成員。也就是說,雖然抽象類中的一些方法和屬性可能已實現,但其他成員(抽象成員)可能已定義其簽名,但沒有實現。從抽象類派生的具體子類定義這些方法和屬性。

as 關鍵字將物件強制轉換為不同的型別。因此,它類似於 TypeA varA = (TypeA) varB 語法。區別在於,如果物件是不可相容的型別,則此關鍵字將返回 null,而前者方法在這種情況下會引發型別轉換異常。

另請參閱

[編輯 | 編輯原始碼]

base 關鍵字描述了你希望參考基類以獲取所需資訊,而不是在當前例項化類中。

base 類是當前實現類繼承自的類。在建立沒有定義基類的類時,編譯器會自動使用 System.Object 基類。

因此,下面的兩個宣告是等效的。

public class MyClass
{
}

public class MyClass : System.Object
{
}

使用 base 關鍵字的一些原因是

  • 將資訊傳遞給基類的建構函式
public class MyCustomException : System.Exception
{
     public MyCustomException() : base() {}

     public MyCustomerException(string message, Exception innerException) : base(message,innerException) {}

     // ......
}
  • 呼叫基類中的變數,其中新實現的類正在覆蓋其行為
public class MyBaseClass
{
     protected string className = "MyBaseClass";
}

public class MyNewClass : MyBaseClass
{
     protected new string className = "MyNewClass";

     public override string BaseClassName
     {
          get { return base.className; }
     }
}
  • 呼叫基類中的方法。當你想在方法中新增內容,但仍保留基礎實現時,這很有用。
// Necessary using's here

public class _Default : System.Web.UI.Page
{
     protected void InitializeCulture()
     {
          System.Threading.Thread.CurrentThread.CurrentUICulture =
                              CultureInfo.GetSpecificCulture(Page.UICulture);

          base.InitializeCulture();
     }
}


bool 關鍵字用於欄位、方法屬性 和變數宣告,以及在 強制轉換typeof 操作中,作為 .NET 框架結構 System.Boolean 的別名。也就是說,它表示 truefalse 的值。與 C++ 不同,C++ 的 布林 實際上是 整數,C# 中的 bool 是它自己的資料型別,不能轉換為任何其他基本型別。

break 關鍵字用於退出迴圈或 switch 塊。

break 用於迴圈中
int x;
 
while (x < 20){

   if (x > 10) break;

   x++;
}

只要 x 小於 20,while 迴圈就會遞增 x。但是當 x 遞增到 10 時,if 語句中的條件變為 true,因此 break 語句導致 while 迴圈被中斷,執行將在閉合括號後繼續。

break 用於 switch 塊中
int x;

switch (x)
    {
    case 0:
        Console.WriteLine("x is 0");
        break;
    case 1:
        Console.WriteLine("x is 1");
        break;
    case 2:
        // falls through
    case 3:
        Console.WriteLine("x is 2 or 3");
        break;
    }

當程式進入 switch 塊時,它將搜尋為 true 的 case 語句。一旦找到,它將讀取所有進一步列印的語句,直到找到 break 語句。在上面的例子中,如果 x 是 0 或 1,控制檯將只打印它們各自的值,然後跳出語句。但是,如果 x 的值是 2 3,程式將讀取相同的後續語句,直到到達 break 語句。為了不向任何閱讀程式碼的人顯示對 2 的處理與 3 相同,良好的程式設計實踐是在 falling-through 的 case 後面添加註釋,如“falls through”。


byte 關鍵字用於欄位、方法屬性 和變數宣告,以及在 強制轉換typeof 操作中,作為 .NET 框架結構 System.Byte 的別名。也就是說,它表示一個 8 位無符號整數,其值範圍為 0 到 255。


case 關鍵字通常用於 switch 語句中。


catch 關鍵字用於識別 語句語句塊 以供執行,如果在封閉的 try 塊的主體中發生異常。catch 子句位於 try 子句之前,可以選擇後跟 finally 子句。


char 關鍵字用於欄位、方法屬性 和變數宣告,以及在 強制轉換typeof 操作中,作為 .NET 框架結構 System.Char 的別名。也就是說,它表示一個 Unicode 字元,其值範圍為 0 到 65,535。


checkedunchecked 運算子用於控制整數型別算術運算和轉換的溢位檢查上下文。它檢查是否發生溢位(這是預設設定)。

另請參閱


關鍵字 class 用於宣告一個


關鍵字 const 用於在欄位和區域性變數宣告中使變數為 常量。因此,它與宣告它的類或程式集相關聯,而不是與類的例項或方法呼叫相關聯。在宣告之外為該變數賦值是語法上無效的。

進一步閱讀

關鍵字 continue 可用於方法中的任何迴圈內。它的作用是結束當前迴圈迭代並進入下一個迴圈迭代。如果在 for 迴圈內執行,則會執行迴圈結束語句(就像正常迴圈終止一樣)。


關鍵字 decimal 用於欄位、方法屬性 和變數宣告以及在 強制轉換typeof 操作中,作為 .NET Framework 結構 System.Decimal 的別名。也就是說,它表示一個帶符號的 128 位十進位制數,其值為 0 或一個具有 28 或 29 位精度的十進位制數,範圍在 之間,或者在 之間。


關鍵字 default 可用於 switch 語句或泛型程式碼中:[1]

  • switch 語句:指定預設標籤。
  • 泛型程式碼:指定型別引數的預設值。對於引用型別,這將為 null,對於值型別,這將為零。

參考文獻

[edit | edit source]
  1. "default (C# Reference)". http://msdn.microsoft.com/en-us/: MSDN. Retrieved 2011-08-09. {{cite web}}: External link in |location= (help)


關鍵字 delegate 用於宣告一個 委託。委託是一種程式設計構造,用於獲取對類方法的可呼叫引用的。


關鍵字 do 用於標識一個 do ... 迴圈 的開始。


關鍵字 double 用於欄位、方法屬性 和變數宣告以及在 強制轉換typeof 操作中,作為 .NET Framework 結構 System.Double 的別名。也就是說,它表示一個 IEEE 754、64 位帶符號二進位制浮點數,其值為 負 0正 0負無窮大正無窮大非數 或一個範圍在 之間,或者在 之間。


關鍵字 else 用於標識 else 子句,它屬於 if 語句的一部分,其語法如下:

if-statement ::= "if" "(" condition ")" if-body "else" else-body
condition ::= boolean-expression
if-body ::= statement-or-statement-block
else-body ::= statement-or-statement-block

else 子句緊跟在 if-body 之後。當 conditionfalse 時,它提供要執行的程式碼。將 else-body 設定為另一個 if 語句會建立一個常見的 cascade 結構,包含 ifelse ifelse ifelse ifelse 語句。

using System;

public class IfStatementSample
{
    public void IfMyNumberIs()
    {
        int myNumber = 5;
        if (myNumber == 4)
            Console.WriteLine("This will not be shown because myNumber is not 4.");
        else if(myNumber < 0)
        {
            Console.WriteLine("This will not be shown because myNumber is not negative.");
        }
        else if(myNumber%2 == 0)
            Console.WriteLine("This will not be shown because myNumber is not even.");
        else
        {
            Console.WriteLine("myNumber does not match the coded conditions, so this sentence will be shown!");
        }
    }
}

上面的示例只檢查 myNumber 是否小於 0,前提是 myNumber 不等於 4。它依次檢查 myNumber%2 是否為 0,前提是 myNumber 不小於 0。由於所有條件都不滿足,因此它執行最後 else 子句的主體部分。


關鍵字 enum 用於標識 列舉


關鍵字 event 用於宣告 事件


通用

[edit | edit source]

當值被隱式轉換時,執行時不需要開發人員在程式碼中進行任何轉換,即可將值轉換為新型別。

以下示例中,開發人員正在進行顯式轉換

// Example of explicit casting.
float fNumber = 100.00f;
int iNumber = (int) fNumber;

開發人員告訴執行時:“我知道我在做什麼,強制進行此轉換。”

隱式轉換意味著執行時不需要任何提示即可進行轉換。以下是一個示例。

// Example of implicit casting.
byte bNumber = 10;
int iNumber = bNumber;

關鍵字

[edit | edit source]

請注意,開發人員不需要進行任何轉換。隱式轉換的特別之處在於,轉換的上下文是完全無損的,即轉換到此型別不會丟失任何資訊,因此可以無憂無慮地轉換回來。

關鍵字 explicit 用於建立型別轉換運算子,這些運算子只能透過指定顯式型別轉換來使用。

此結構有助於軟體開發人員編寫更易讀的程式碼。使用顯式轉換名稱可以清楚地表明正在進行轉換。

class Something 
{
  public static explicit operator Something(string s)
  {
     // Convert the string to Something
  }
}

string x = "hello";

// Implicit conversion (string to Something) generates a compile time error
Something s = x;

// This statement is correct (explicit type name conversion)
Something s = (Something) x;


關鍵字 extern 指示正在呼叫的方法存在於 DLL 中。

名為 tlbimp.exe 的工具可以建立包裝程式集,使 C# 可以像使用 .NET 程式集一樣與 DLL 互動,即使用建構函式例項化它,呼叫它的方法。

舊的 DLL 不適用於此方法。相反,您必須顯式地告訴編譯器要呼叫哪個 DLL、要呼叫哪個方法以及要傳遞哪些引數。由於引數型別非常重要,您也可以顯式地定義要傳遞給方法的引數的型別。

以下是一個示例

using System;
using System.Runtime.InteropServices;

namespace ExternKeyword
{
     public class Program
     {
          static void Main()
          {
               NativeMethods.MessageBoxEx(IntPtr.Zero, "Hello there", "Caption here", 0, 0);
          }
     }
  
     public class NativeMethods
     {
          [DllImport("user32.dll")]
          public static extern MessageBoxEx(IntPtr hWnd, string lpText, string lpCaption, uint uType, short wLanguageId);
     }
}

[DllImport("user32.dll")] 告訴編譯器要引用哪個 DLL。Windows 會根據 PATH 環境變數的定義搜尋檔案,因此它會在失敗之前搜尋這些路徑。

該方法也是靜態的,因為 DLL 可能不理解如何“建立”,因為 DLL 可以用不同的語言建立。這允許直接呼叫該方法,而不是例項化它,然後使用它。


C# 關鍵字
abstract as base bool break
byte case catch char checked
class const continue decimal default
delegate do double else enum
event explicit extern false finally
fixed float for foreach goto
if implicit in int interface
internal is lock long namespace
new null object operator out
override params private protected public
readonly ref return sbyte sealed
short sizeof stackalloc static string
struct switch this throw true
try typeof uint ulong unchecked
unsafe ushort using var virtual
void volatile while
特殊 C# 識別符號(上下文關鍵字)
add alias async await dynamic
get global nameof partial remove
set value when where yield
上下文關鍵字(用於查詢)
ascending by descending equals from
group in into join let
on orderby select where

關鍵字 false 是一個 布林 常量值。


關鍵字 finally 用於標識 try-catch 塊之後的語句語句塊,無論關聯的 try 塊是否遇到異常,都會執行,即使在 return 語句之後也會執行。finally 塊用於執行清理活動。


關鍵字 fixed 用於阻止垃圾收集器重新定位變數。您只能在不安全的上下文中使用它。

fixed (int *c = &shape.color) {
  *c = Color.White; 
}

如果您使用的是 C# 2.0 或更高版本,則 fixed 也可用於宣告固定大小的陣列。這在建立與 COM 專案或 DLL 互動的程式碼時很有用。

您的陣列必須由以下基本型別之一組成:boolbytechardoublefloatintlongsbyteshortulongushort

protected fixed int monthDays[12];


關鍵字 float 用於欄位、方法屬性 和變數宣告,以及在轉換typeof 操作中,作為 .NET Framework 結構 System.Single 的別名。也就是說,它表示 IEEE 754、32 位有符號二進位制浮點數,其值為負 0正 0負無窮大正無窮大非數字,或者介於 或從 之間的數字。


關鍵字 for 用於標識 for 迴圈


關鍵字 foreach 用於標識 foreach 迴圈

// example of foreach to iterate over an array
public static void Main() {
  int[] scores = new int [] { 54, 78, 34, 88, 98, 12 };

    int total = 0;
  foreach (int score in scores) {
      total += score;
  }

  int averageScore = total/scores.Length;
}


關鍵字 goto 將操作流程返回到它後面的標籤。標籤可以透過在任何單詞後面新增冒號來建立。例如:

thelabel:       // This is a label
 System.Console.WriteLine("Blah blah blah");
 goto thelabel; // Program flow returns to thelabel

使用 `goto` 語句存在很大爭議,因為如果濫用,會造成程式碼跳來跳去,混亂且難以閱讀。實際上,它很少有必要使用,因為通常可以使用組織性更好的 for 迴圈while 迴圈 來實現相同的效果。

關鍵字 if 用於標識一個 if 語句,其語法如下:

if-statement ::= "if" "(" condition ")" if-body ["else" else-body]
condition ::= boolean-expression
if-body ::= statement-or-statement-block
else-body ::= statement-or-statement-block

如果 condition 的值為 true,則執行 if-body。大括號 ("{" 和 "}") 允許 if-body 包含多個語句。可以選擇性地在 if-body 後面緊跟一個 else 子句,用於提供在 conditionfalse 時執行的程式碼。如果將 else-body 設定為另一個 if 語句,就會形成常見的 if, else if, else if, else if, else 語句級聯。

using System;

public class IfStatementSample
{
    public void IfMyNumberIs()
    {
        int myNumber = 5;
        if (myNumber == 4)
            Console.WriteLine("This will not be shown because myNumber is not 4.");
        else if(myNumber < 0)
        {
            Console.WriteLine("This will not be shown because myNumber is not negative.");
        }
        else if(myNumber%2 == 0)
            Console.WriteLine("This will not be shown because myNumber is not even.");
        else
        {
            Console.WriteLine("myNumber does not match the coded conditions, so this sentence will be shown!");
        }
    }
}

if 語句中使用的布林表示式通常包含以下一個或多個運算子:

運算子 含義 運算子 含義
< < > >
== == != !=
<= <= >= >=
&& && || ||
! !

另請參閱 else

通用

[edit | edit source]

當隱式轉換值時,執行時不需要開發人員在程式碼中進行任何強制轉換,即可將值轉換為新的型別。

以下示例中,開發人員正在進行顯式轉換

// Example of explicit casting.
float fNumber = 100.00f;
int iNumber = (int) fNumber;

開發人員告訴執行時:“我知道我在做什麼,強制進行此轉換。”

隱式轉換意味著執行時不需要任何提示即可進行轉換。以下是一個示例。

// Example of implicit casting.
byte bNumber = 10;
int iNumber = bNumber;

請注意,開發人員無需進行任何強制轉換。隱式轉換的特殊之處在於,轉換到的上下文完全無損,即轉換到此型別不會丟失任何資訊。因此,可以放心地將其轉換回原始型別。

關鍵字

[edit | edit source]

關鍵字 implicit 用於型別定義如何隱式轉換。它用於定義無需顯式強制轉換即可轉換到的型別。

例如,讓我們考慮一個 `Fraction` 類,它將儲存分子(除法運算子上方的數字)和分母(除法運算子下方的數字)。我們將新增一個屬性,以便可以將值轉換為 float

public class Fraction
{
     private int nominator;
     private int denominator;

     public Fraction(int nominator1, int denominator1)
     {
          nominator = nominator1;
          denominator = denominator1;
     }

     public float Value { get { return (float)_nominator/(float)_denominator; } }

     public static implicit operator float(Fraction f)
     {
          return f.Value;
     }

     public override string ToString()
     {
          return _nominator + "/" + _denominator;
     }
}

public class Program
{
    [STAThread]
     public static void Main(string[] args)
     {
          Fraction fractionClass = new Fraction(1, 2);
          float number = fractionClass;

          Console.WriteLine("{0} = {1}", fractionClass, number);
     }
}

重申一下,隱式轉換到的值必須以原始類可以轉換回的格式儲存資料。如果這不可能,並且範圍縮小(例如,將 double 轉換為 int),請使用顯式運算子。


關鍵字 in 用於標識在 foreach 迴圈 中列舉的集合。

關鍵字 in 也可用於查詢,例如,`'from item in dataset'。緊跟在上下文關鍵字 from 後面的是一個範圍變數,代表資料集中的一個專案。要查詢的資料集在上下文關鍵字 in 後面定義。另請參閱 ascending, descending, in, orderby, selectwhere


關鍵字 int 用於欄位、方法屬性 和變數宣告,以及在 強制轉換typeof 操作中用作 .NET Framework 結構 System.Int32 的別名。也就是說,它表示一個 32 位有符號整數,其值範圍為 -2,147,483,648 到 2,147,483,647。


關鍵字 interface 用於宣告一個 介面。介面為程式設計師提供了一種構造方法,用於建立可以宣告但未實現方法、屬性、委託、事件和索引器的型別。

良好的程式設計實踐是為介面提供與類不同的名稱,這些名稱以 I 開頭和/或以 ...able 結尾,例如 IRunRunnableIRunnable


關鍵字 internal 是一個 訪問修飾符,用於欄位、方法屬性 宣告,以使欄位、方法或屬性對其封閉程式集 內部。也就是說,它只在實現它的程式集中 可見


關鍵字 is 將一個物件與一個型別進行比較,如果它們相同或屬於同一“種類”(物件 繼承 型別),則返回 true。因此,此關鍵字用於檢查型別相容性,通常在 強制轉換(轉換)源型別到目標型別之前,以確保不會丟擲型別轉換異常。對 null 變數使用 is 始終返回 false

此程式碼片段展示了一個示例用法

System.IO.StreamReader reader = new StreamReader("readme.txt");
bool b = reader is System.IO.TextReader;

// b is now set to true, because StreamReader inherits TextReader


關鍵字 lock 允許程式碼段獨佔使用資源,這在多執行緒應用程式中非常有用。如果程式碼段嘗試鎖定某個物件時,該物件已經被鎖定,則該程式碼段的執行緒將被阻塞,直到物件可用為止。

using System;
using System.Threading;

class LockDemo
{
    private static int number = 0;
    private static object lockObject = new object();
    
    private static void DoSomething()
    {
        while (true)
        {
            lock (lockObject)
            {
                int originalNumber = number;
                
                number += 1;
                Thread.Sleep((new Random()).Next(1000)); // sleep for a random amount of time
                number += 1;
                Thread.Sleep((new Random()).Next(1000)); // sleep again
                
                Console.Write("Expecting number to be " + (originalNumber + 2).ToString());
                Console.WriteLine(", and it is: " + number.ToString());
                // without the lock statement, the above would produce unexpected results, 
                // since the other thread may have added 2 to the number while we were sleeping.
            }
        }
    }
    
    public static void Main()
    {
        Thread t = new Thread(new ThreadStart(DoSomething));
        
        t.Start();
        DoSomething(); // at this point, two instances of DoSomething are running at the same time.
    }
}

lock 語句的引數必須是物件引用,而不是值型別。

class LockDemo2
{
    private int number;
    private object obj = new object();
    
    public void DoSomething()
    {
        lock (this) // ok
        {
            ...
        }
        
        lock (number) // not ok, number is not a reference
        {
            ...
        }
        
        lock (obj) // ok, obj is a reference
        {
            ...
        }
    }
}


關鍵字 long 用於欄位、方法屬性 和變數宣告,以及在 強制轉換typeof 操作中用作 .NET Framework 結構 System.Int64 的別名。也就是說,它表示一個 64 位有符號整數,其值範圍為 -9,223,372,036,854,775,808 到 9,223,372,036,854,775,807。


關鍵字 namespace 用於為類、結構和型別宣告提供 名稱空間


關鍵字 new 有兩種不同的含義:

  1. 它是一個運算子,用於請求其引數標識的類的新的例項。
  2. 它是一個修飾符,用於顯式隱藏成員。

例如,請參見下面的程式碼

public class Car
{
    public void go()
    {
    }
}

Car theCar = new Car();       // The new operator creates a Car instance

int i = new int();            // Identical to … = 0;

public class Lamborghini : Car
{
    public new void go()      // Hides Car.go() with this method
    {
    }
}


關鍵字 null 表示 引用型別變數的空值,即任何從 System.Object 派生的型別變數的空值。在 C# 2.0 中,null 也表示可空 型別變數的空值。


關鍵字 object 用於欄位、方法屬性 和變數宣告,以及在 強制轉換typeof 操作中,作為 .NET Framework 結構 System.Object 的別名。也就是說,它表示所有其他 引用型別 派生的基類。在某些平臺上,引用的大小為 32 位,而在其他平臺上,它為 64 位。


關鍵字 operator 允許類過載算術運算子和強制轉換運算子。

public class Complex
{
    private double re, im;
    
    public double Real
    {
        get { return re; }
        set { re = value; }
    }
    
    public double Imaginary
    {
        get { return im; }
        set { im = value; }
    }
    
    // binary operator overloading
    public static Complex operator +(Complex c1, Complex c2)
    {
        return new Complex() { Real = c1.Real + c2.Real, Imaginary = c1.Imaginary + c2.Imaginary };
    }
    
    // unary operator overloading
    public static Complex operator -(Complex c)
    {
        return new Complex() { Real = -c.Real, Imaginary = -c.Imaginary };
    }
    
    // cast operator overloading (both implicit and explicit)
    public static implicit operator double(Complex c)
    {
        // return the modulus: sqrt(x^2 + y^2)
        return Math.Sqrt(Math.Pow(c.Real, 2) + Math.Pow(c.Imaginary, 2));
    }
    
    public static explicit operator string(Complex c)
    {
        // we should be overloading the ToString() method, but this is just a demonstration
        return c.Real.ToString() + " + " + c.Imaginary.ToString() + "i";
    }
}

public class StaticDemo
{
    public static void Main()
    {
        Complex number1 = new Complex() { Real = 1, Imaginary = 2 };
        Complex number2 = new Complex() { Real = 4, Imaginary = 10 };
        Complex number3 = number1 + number2; // number3 now has Real = 5, Imaginary = 12
        
        number3 = -number3; // number3 now has Real = -5, Imaginary = -12
        double testNumber = number3; // testNumber will be set to the absolute value of number3
        Console.WriteLine((string)number3); // This will print "-5 + -12i".
        // The cast to string was needed because that was an explicit cast operator.
    }
}

關鍵字 out 明確指定變數應以 引用方式 傳遞給方法,並在該方法中設定。使用此關鍵字的變數在方法呼叫之前 不能 初始化,以確保開發人員瞭解其預期效果。使用此關鍵字要求被呼叫方法在返回之前使用此修飾符設定變數。使用 out 還要求開發人員即使在呼叫程式碼中也要指定關鍵字,以確保在讀取程式碼的開發人員中易於看到變數的值將在其他地方更改,這在分析程式流程時很有用。

以下是用 out 傳遞變數的示例。

void CallingMethod()
{
    int i;
    SetDependingOnTime(out i);
    // i is now 10 before/at 12 am, or 20 after
}

void SetDependingOnTime(out int iValue)
{
    iValue = DateTime.Now.Hour <= 12 ? 10 : 20;
}


C# 關鍵字
abstract as base bool break
byte case catch char checked
class const continue decimal default
delegate do double else enum
event explicit extern false finally
fixed float for foreach goto
if implicit in int interface
internal is lock long namespace
new null object operator out
override params private protected public
readonly ref return sbyte sealed
short sizeof stackalloc static string
struct switch this throw true
try typeof uint ulong unchecked
unsafe ushort using var virtual
void volatile while
特殊 C# 識別符號(上下文關鍵字)
add alias async await dynamic
get global nameof partial remove
set value when where yield
上下文關鍵字(用於查詢)
ascending by descending equals from
group in into join let
on orderby select where

關鍵字 override 用於宣告覆蓋函式,該函式擴充套件了具有相同名稱的基類函式。

進一步閱讀

關鍵字 params 用於描述將一組引數傳遞給方法的情況,但引數的數量並不重要,因為它們可能會有所不同。由於數量不重要,params 關鍵字必須是方法簽名中的最後一個變數,以便編譯器可以在處理 params 之前處理已定義的引數。

以下是在哪裡有效和無效的示例。

// This works
public static void AddToShoppingBasket(decimal total, params string[] items)
{
  // ....
}

// This works
public static void AddToShoppingBasket(decimal total, int totalQuantity, params string[] items)
{
  // ....
}


// THIS DOES NOT WORK                  <-------------------->
public static void AddToShoppingBasket(params string[] items, decimal total, int totalQuantity)
{
  // ....
}

一個很好的例子是 String.Format 方法。 String.Format 方法允許使用者傳入一個格式化為其要求的字串,然後傳入許多引數以插入字串中的值。這是一個例子。

public static string FormatMyString(string format, params string[] values)
{
     string myFormat = "Date: {0}, Time: {1}, WeekDay: {1}";
     return String.Format(myFormat, DateTime.Now.ToShortDateString(), DateTime.Now.ToShortTimeString(), DateTime.Now.DayOfWeek);
}

// Output will be something like:
//
// Date: 7/8/2007, Time: 13:00, WeekDay: Tuesday;
//

String.Format 方法接收了一個字串,並將 {0}、{1}、{2} 替換為第 1、第 2 和第 3 個引數。如果 params 關鍵字不存在,則 String.Format() 將需要無限數量的過載才能滿足每種情況。

public string Format(string format, string param1)
{
  // .....
}

public string Format(string format, string param1, string param2)
{
  // .....
}

public string Format(string format, string param1, string param2, string param3)
{
  // .....
}

public string Format(string format, string param1, string param2, string param3, string param4)
{
  // .....
}

public string Format(string format, string param1, string param2, string param3, string param4, string param5)
{
  // .....
}

// To infinitum


關鍵字 private 用於欄位、方法屬性 宣告,以使欄位、方法或屬性對其封閉類 私有。也就是說,它在類之外 不可見


關鍵字 protected 用於欄位、方法屬性 宣告,以使欄位、方法或屬性對其封閉類 受保護。也就是說,它在類之外 不可見


關鍵字 public 用於欄位、方法屬性 宣告,以使欄位、方法或屬性對其封閉類 公開。也就是說,它在任何類中都是 可見 的。


關鍵字 readonlyconst 關鍵字密切相關,除了允許使用此修飾符的變數在建構函式中初始化,以及與類例項(物件)而不是類本身相關聯之外。

此關鍵字的主要用途是允許變數根據呼叫了哪個建構函式來獲取不同的值(如果類有多個建構函式),同時仍然確保開發人員知道一旦建立了物件,該值在程式碼中永遠不會被有意或無意地更改。

這是一個示例用法,假設它位於名為 SampleClass 的類中。

readonly string s;

SampleClass()
{
    s = "Hello!";
}


關鍵字 ref 明確指定變數應以 引用方式 傳遞而不是以 值方式 傳遞。

開發人員可能希望透過引用傳遞變數,特別是在 值型別 的情況下。如果透過引用傳遞變數,實際上只向函式傳送一個指標,這會降低方法呼叫的成本,因為它會涉及大量資料的複製,這是 C# 在通常傳遞值型別時所做的。

透過引用傳遞變數的另一個常見原因是讓被呼叫方法修改其值。由於允許這樣做,C# 始終強制在方法呼叫中指定透過引用傳遞的值,這是許多其他程式語言所沒有的。這使讀取程式碼的開發人員可以輕鬆地發現可能暗示型別的值已在方法中更改的位置,這在分析程式流程時很有用。

透過引用傳遞值並不意味著被呼叫方法 必須 修改值;有關此方面,請參見 out 關鍵字。

透過引用傳遞要求傳遞的變數已初始化。

以下是用引用傳遞變數的示例。

void CallingMethod()
{
    int i = 24;
    if (DoubleIfEven(ref i))
        Console.WriteLine("i was doubled to {0}", i); // outputs "i was doubled to 48"
}

bool DoubleIfEven(ref int iValue)
{
    if (iValue%2 == 0)
    {
        iValue *= 2;
        return true;
    }
    return false;
}


關鍵字 return 用於從 方法屬性 訪問器返回執行。如果 方法屬性 訪問器具有返回型別,則 return 關鍵字後跟要返回的值。


關鍵字 sbyte 用於欄位、方法屬性 和變數宣告,以及在 強制轉換typeof 操作中,作為 .NET Framework 結構 System.SByte 的別名。也就是說,它表示一個 8 位有符號整數,其值範圍為 -128 到 127。


關鍵字 sealed 用於指定類不能被繼承。以下示例顯示了它可能在其中使用的上下文。

public sealed class
{
    ...
}

注意: sealed 類繼承與 Java 中的final類相同。


關鍵字 short 用於欄位、方法屬性 和變數宣告,以及在 強制轉換typeof 操作中,作為 .NET Framework 結構 System.Int16 的別名。也就是說,它表示一個 16 位有符號整數,其值範圍為 -32,768 到 32,767。

關鍵字 sizeof 返回物件需要多少位元組才能儲存。

一個示例用法

int i = 123456;

Console.WriteLine("Storing i, a {0}, requires {1} bytes, or {2} bits.",
i.GetType(), sizeof(i), sizeof(i)*8);

// outputs "Storing i, a System.Int32, requires 4 bytes, or 32 bits."

關鍵字 stackalloc 用於不安全的程式碼上下文中,在堆疊上分配記憶體塊。

int* fib = stackalloc int[100];

在上面的示例中,在堆疊上分配了一個大小足以容納 100 個 int 型別元素的記憶體塊,而不是在堆上;該塊的地址儲存在指標 fib 中。此記憶體不受垃圾回收的約束,因此不必固定(透過 fixed)。記憶體塊的生存期僅限於定義它的方法的生存期(無法在方法返回之前釋放記憶體)。

stackalloc 僅在區域性變數初始化器中有效。

由於涉及 Pointer 型別,因此 stackalloc 需要不安全的上下文。請參見不安全的程式碼和指標。

stackalloc 與 C 執行時庫中的 _alloca 相似。

注意* - 來自 MSDN


關鍵字 static 用於將 或類成員(方法屬性欄位變數)宣告為 靜態。宣告為 靜態 只有 靜態 成員,這些成員與整個類相關聯,而不是與類 例項 相關聯。


關鍵字 string 用於欄位、方法屬性 和變數宣告,以及在 強制轉換typeof 操作中,作為 System.String 的別名。也就是說,它表示一個不可變的字元序列。


關鍵字 struct 用於宣告一個 結構體,即一個充當輕量級值型別


關鍵字 switch 語句是一個控制語句,透過將控制傳遞到其主體內的 case 語句之一來處理多個選擇和列舉。

這是一個 switch 語句的示例

int currentAge = 18;

switch (currentAge)
{
case 16:
    Console.WriteLine("You can drive!");
    break;
case 18:
    Console.WriteLine("You're finally an adult!");
    break;
default:
    Console.WriteLine("Nothing exciting happened this year.");
    break;
}
Console Output
You're finally an adult! 	


關鍵字 this例項方法例項屬性中用於引用當前類例項。也就是說,this 指向呼叫其包含方法或屬性的物件。它也用於定義 擴充套件方法


關鍵字 throw 用於丟擲異常物件。

關鍵字 true 是一個 布林常量值。因此

 while(true)

將建立一個無限迴圈。


關鍵字 try 用於標識語句語句塊作為異常處理序列的主體。異常處理序列的主體必須後跟一個 catch 子句、一個 finally 子句或兩者。

try 
{
    foo();
} 
catch(Exception Exc)
{
    throw new Exception ("this is the error message", Exc);
}

關鍵字 typeof 當傳遞一個類名時,它返回 System.Type 類的例項。它類似於關鍵字 sizeof,因為它返回一個值而不是開始一段程式碼(塊)(參見 iftrywhile)。

一個例子

using System;

namespace MyNamespace
{
    class MyClass
    {
        static void Main(string[] args)
        {
            Type t = typeof(int);
            Console.Out.WriteLine(t.ToString());
            Console.In.Read();
        }
    }
}

輸出將是

System.Int32

需要注意的是,與 sizeof 不同,只能將類名本身而不是變數傳遞給 typeof,如這裡所示

using System;

namespace MyNamespace
{
    class MyClass2
    {
        static void Main(string[] args)
        {
            char ch;
            
            // This line will cause compilation to fail
            Type t = typeof(ch);
            Console.Out.WriteLine(t.ToString());
            Console.In.Read();
        }
    }
}

有時,類將包含它們自己的 GetType() 方法,該方法將類似於,如果不是完全相同,則類似於 typeof


關鍵字 uint 用於欄位、方法屬性 和變數宣告以及強制轉換typeof 操作,作為 .NET Framework 結構 System.UInt32 的別名。也就是說,它表示一個 32 位無符號整數,其值範圍為 0 到 4,294,967,295。


關鍵字 ulong 用於欄位、方法屬性 和變數宣告以及強制轉換typeof 操作,作為 .NET Framework 結構 System.UInt64 的別名。也就是說,它表示一個 64 位無符號整數,其值範圍為 0 到 18,446,744,073,709,551,615。

</noinclude>

關鍵字 unchecked 在執行整數運算時會阻止溢位檢查。它可以用作單個表示式的運算子,也可以用作整個程式碼塊的語句。

int x, y, z;
x = 1222111000;
y = 1222111000;

// used as an operator
z = unchecked(x*y);

// used as a statement
unchecked {
  z = x*y;
  x = z*z;
}


關鍵字 unsafe 可用於修改過程或定義使用不安全程式碼的程式碼塊。如果程式碼使用“地址 of”(&)或指標運算子(*),則該程式碼是不安全的。

為了讓編譯器編譯包含此關鍵字的程式碼,您必須在使用 Microsoft C-Sharp 編譯器時使用 unsafe 選項。

class MyClass {
  public static void Main() {
    int x = 2;
    // example of unsafe to modify a code block
    unsafe {
      DoSomething(&x);
    }
  }

  // example of unsafe to modify a procedure
  unsafe static void DoSomething(int *msg) {
    Console.WriteLine(*msg);
  }
}


關鍵字 ushort 用於欄位、方法屬性 和變數宣告以及強制轉換typeof 操作,作為 .NET Framework 結構 System.UInt16 的別名。也就是說,它表示一個 16 位無符號整數,其值範圍為 0 到 65,535。


關鍵字 using 在 C# 中具有兩個完全不相關的含義,具體取決於它是用作指令還是語句。

指令

[edit | edit source]

using 作為指令解析非限定型別引用,以便開發人員不必指定完整的名稱空間。

例子

using System;
 
// A developer can now type ''Console.WriteLine();'' rather than ''System.Console.WriteLine()''.

using 還可以為引用型別提供命名空間別名

例子

using utils = Company.Application.Utilities;

語句

[edit | edit source]

using 作為語句會自動呼叫指定物件的 dispose。物件必須實現 IDisposable 介面。只要它們是相同型別,就可以在一個語句中使用多個物件。

例子

using (System.IO.StreamReader reader = new StreamReader("readme.txt"))
{
    // read from the file
}
 
// The file readme.txt has now been closed automatically.

using (Font headerFont = new Font("Arial", 12.0f),
            textFont = new Font("Times New Roman", 10.0f))
{
    // Use headerFont and textFont.
}

// Both font objects are closed now.


關鍵字 var 可用於在宣告變數時代替型別,以允許編譯器推斷變數的型別。此功能可用於縮短變數宣告,尤其是在例項化泛型型別時,並且在使用 LINQ 表示式時也是必需的(因為查詢可能會生成非常複雜的型別)。

以下

int num = 123;
string str = "asdf";
Dictionary<int, string> dict = new Dictionary<int, string>();

等效於

var num = 123;
var str = "asdf";
var dict = new Dictionary<int, string>();

var 不會建立“變體”型別;型別只是由編譯器推斷的。在無法推斷型別的場合,編譯器會生成錯誤

var str; // no assignment, can't infer type

void Function(var arg1, var arg2) // can't infer type
{
    ...
}

注意:Var 不是關鍵字


關鍵字 virtual 應用於方法宣告以指示該方法可以在子類中被重寫。如果未應用 virtual 關鍵字並且在子類中定義了與父類中相同簽名的方法,則父類中的方法將被子類實現隱藏。換句話說,只有使用此關鍵字才能真正實現函式的 多型性

注意:與 Java 相比,如果方法是final,則該方法不是虛擬的。這是由於不同的 設計理念


關鍵字 void 用於 方法 簽名以宣告不返回值的方法。宣告為 void 返回型別的方法無法向其包含的任何 return 語句提供任何引數。

例子

public void WorkRepeatedly (int numberOfTimes)
{
    for(int i = 0; i < numberOfTimes; i++)
        if(EarlyTerminationIsRequested)
            return;
        else
            DoWork();
}


關鍵字 volatile 用於宣告一個變數,該變數可能會隨著時間的推移而改變其值,原因是外部程序、系統硬體或另一個併發執行的執行緒進行了修改。

您應該在成員變數宣告中使用此修飾符,以確保無論何時讀取該值,您都始終獲得變數的最新(最新)值。

class MyClass
{
  public volatile long systemclock;
}


此關鍵字自 .NET Framework 1.1(Visual Studio 2003)起成為 C# 程式語言的一部分。


關鍵字 while 用於標識一個 while 迴圈

C# 特殊識別符號


關鍵字 addremove 允許您在將委託新增到事件或從事件中刪除委託時執行程式碼。其用法類似於屬性的 getset 關鍵字

public event MyDelegateType MyEvent
{
    add
    {
        // here you can use the keyword "value" to access the delegate that is being added
        ...
    }
    
    remove
    {
        // here you can use the keyword "value" to access the delegate that is being removed
        ...
    }
}

將委託新增到事件時,將執行 add 塊中的程式碼。類似地,將委託從事件中刪除時,將執行 remove 塊中的程式碼。


關鍵字 alias 用於指示外部別名

當您需要使用同一程式集的多個版本或具有相同完全限定型別名的程式集時,您需要使用 aliasextern 關鍵字為每個版本提供不同的別名。

例子

extern alias AppTools;
extern alias AppToolsV2;

要使用每個版本的型別名,您有運算子 :: .

例子

AppTools::MainTool tool_v1 = new AppTools::MainTool();
AppToolsV2::MainTool tool_v2 = new AppToolsV2::MainTool();

然而,這僅僅告訴編譯器有幾個程式集存在型別名稱衝突。為了將每個程式集的哪些內容與別名匹配起來,你需要在編譯器選項中區分原始碼。在 `dotNet` 命令列中,這些選項應該是

/r:AppTools=AppToolsv100.dll /r:AppToolsV2=AppToolsv200.dll

注意:為了讓它發揮作用,你需要為編譯器提供一個外部程式集(例如,傳遞 `/r:EXTALIAS=XXX.dll`)並在程式碼中標識外部別名(例如 `extern alias EXTALIAS;`)


特殊識別符號 get 用於宣告屬性的讀訪問器。


關鍵字 global 在某些情況下用於解決識別符號之間的歧義。例如,如果類名和名稱空間之間存在衝突,你可以使用關鍵字 global 來訪問名稱空間

namespace MyApp
{
    public static class System
    {
        public static void Main()
        {
            global::System.Console.WriteLine("Hello, World!");
            // if we had just used System.Console.WriteLine, 
            // the compile would think that we referred to a 
            // class named "Console" inside our "System" class.
        }
    }
}

global 然而在以下情況下不起作用,因為我們的 System 類沒有名稱空間

public static class System
{
    public static void Main()
    {
        global::System.Console.WriteLine("Hello, World!");
        // "System" doesn't have a namespace, so the above
        // would be referring to this class!
    }
}


特殊識別符號 partial 用於允許開發人員從不同的檔案構建類,並讓編譯器生成一個類,將所有部分類組合在一起。這對於將類分成單獨的塊非常有用。例如,Visual Studio 2005 將窗體的 UI 程式碼分隔到一個單獨的部分類中,這樣你就可以分別處理業務邏輯。


特殊識別符號 set 用於宣告屬性的寫訪問器。


特殊識別符號 value 用於屬性的寫訪問器中,代表為屬性分配的值。


關鍵字 where 有兩種不同的含義

  1. 它用於指定泛型型別引數的一個或多個約束。
  2. 在 LINQ 中,它用於查詢資料來源並選擇或過濾要返回的元素。


關鍵字 yield 從迭代器返回下一個值或結束迭代。

C# 關鍵字的參考列表位於 [2]。

華夏公益教科書