C Sharp/變量與常量

維基教科書,自由的教學讀本

常量[編輯]

常量就是在程序運行期間維持不變的量,常量也有類型。

字面常量[編輯]

字面常量就是書寫在代碼中固定的數值。

using System;

public class Demo
{
    public static void Main()
    {
        Console.WriteLine(12);
    }
}

其中數字12就是字面常量,其類型為int型。

符號常量[編輯]

變量[編輯]

C#中的欄位(fields), 形參(parameters),局部變量(local variables)都對應於變量。

欄位即類級變量、類的數據成員。又分為「實例變量」(instance variable)與靜態變量。常值欄位要求聲明時就該賦值。欄位的可見性修飾從高到低:public, protected, internal, protected internal, private

局部變量分為常值(存放在assembly data region)與非常值(存放在棧中)。在聲明的作用域中可見。

方法的形參:

  • in修飾,是預設情況。對於值類型(int, double, string)為「傳值」,對於引用類型為「傳引用」。
  • out修飾,被編譯器認為直到方法調用這個名字是非綁定(unbound)的。因此在方法內未賦值就引用輸出參數是非法的。方法內部的正常執行路徑必須對輸出參數賦值。
  • reference修飾,為方法調用前已經bound。方法內部不是必須賦值。
  • params修飾,表示可變參數。必須是形參表最後一個。
// Each pair of lines is what the definition of a method and a call of a 
//   method with each of the parameters types would look like.
// In param:
void MethodOne(int param1)    // definition
MethodOne(variable);          // call

// Out param:
void MethodTwo(out string message)  // definition
MethodTwo(out variable);            // call

// Reference param;
void MethodThree(ref int someFlag)  // definition
MethodThree(ref theFlag)            // call

// Params
void MethodFour(params string[] names)           // definition
MethodFour("Matthew", "Mark", "Luke", "John");   // call