C#中,當使用常數符號const時,編譯器首先從定義常數的模塊的元數據中找出該符號,并直接取出常數的值,然后將之嵌入到編譯后產生的IL代碼中,所以常數在運行時不需要分配任何內存,當然也就無法獲取常數的地址,也無法使用引用了。
如下代碼:
復制代碼 代碼如下:
public class ConstTest
{
public const int ConstInt = 1000;
}
復制代碼 代碼如下:
using System;
class Program
{
public static void Main(string[] args)
{
Console.WriteLine(ConstTest.ConstInt);//結果輸出為1000;
}
}
復制代碼 代碼如下:
public class ConstTest
{
//只能在定義時聲明
public const int ConstInt = 1000;
public readonly int ReadOnlyInt = 100;
public static int StaticInt = 150;
public ConstTest()
{
ReadOnlyInt = 101;
StaticInt = 151;
}
//static 前面不可加修飾符
static ConstTest()
{
//此處只能初始化static變量
StaticInt = 152;
}
}
復制代碼 代碼如下:
class Program
{
public static void Main(string[] args)
{
Console.WriteLine(ConstTest.ConstInt);//輸出1000
Console.WriteLine(ConstTest.StaticInt);//輸出152
ConstTest mc = new ConstTest();
Console.WriteLine(ConstTest.StaticInt);//輸出151
}
}
新聞熱點
疑難解答
圖片精選