const是一個修飾常量的關鍵字,它限定一個變量不允許被改變。使用const在一定程度上可以提高程序的安全性和可靠性,它在程序設計中有著非常重要的作用,給開發人員帶來非常方便的應用。
下面我們來建一個控制臺應用程序作測試:
public class Test{ public readonly string name = "George"; public const string coname = "ABC Company LLC"; public Test(string name) { // readonly 修飾的變量能且只能在 Constructor(構造函數)中被改變 this.name = name; } public string _name { get { return name; } //不可以對readonly修飾的變量進行Set操作 //set //{ // name = value; //} }} class Program{ static void Main(string[] args) { Test obj = new Test("Test"); //readonly的變量不可以修改值,只能在 Constructor(構造函數)中被改變 //obj.name = "New Value"; Console.WriteLine(obj.name); //const 的變量直接通過對象訪問,不需要實例化 Console.WriteLine(Test.coname); Console.Read(); }}以前一直以為 readonly 與 const 的作用是一樣的,現在明白它們之間的區別了,不知道您是否也明白了呢?希望大家有所收獲吧!
新聞熱點
疑難解答
圖片精選