C#中,當(dāng)使用常數(shù)符號const時(shí),編譯器首先從定義常數(shù)的模塊的元數(shù)據(jù)中找出該符號,并直接取出常數(shù)的值,然后將之嵌入到編譯后產(chǎn)生的IL代碼中,所以常數(shù)在運(yùn)行時(shí)不需要分配任何內(nèi)存,當(dāng)然也就無法獲取常數(shù)的地址,也無法使用引用了。
如下代碼:
復(fù)制代碼 代碼如下:
public class ConstTest
{
public const int ConstInt = 1000;
}
復(fù)制代碼 代碼如下:
using System;
class Program
{
public static void Main(string[] args)
{
Console.WriteLine(ConstTest.ConstInt);//結(jié)果輸出為1000;
}
}
復(fù)制代碼 代碼如下:
public class ConstTest
{
//只能在定義時(shí)聲明
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;
}
}
復(fù)制代碼 代碼如下:
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
}
}
新聞熱點(diǎn)
疑難解答
圖片精選