C#中,當使用常數符號const時,編譯器首先從定義常數的模塊的元數據中找出該符號,并直接取出常數的值,然后將之嵌入到編譯后產生的IL代碼中,所以常數在運行時不需要分配任何內存,當然也就無法獲取常數的地址,也無法使用引用了。
如下代碼:
代碼如下:
public class ConstTest
{
public const int ConstInt = 1000;
}
將其編譯成ConstTest.dll文件,并在如下代碼中引用此ConstTest.dll文件。
代碼如下:
using System;
class Program
{
public static void Main(string[] args)
{
Console.WriteLine(ConstTest.ConstInt);//結果
如果將ConstTest重新定義為:
代碼如下:
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;
}
}
重新編譯成ConstTest.dll并向調用程序Main添加此引用后,再編譯調用程序,生成新的Main.exe,即使再次刪除ConstTest.dll文件后,Main.exe運行正常,結果
將Main程序更改如下:
代碼如下:
class Program
{
public static void Main(string[] args)
{
Console.WriteLine(ConstTest.ConstInt);//
如此可以看出,如果某些工程引用到了ConstTest.dll,如果后來因為變動,改變了ConstInt常量的值,即使引用重新編譯的ConstTest.dll,也無法更改Main.exe中的數據(可以把ConstInt值改為其它值,然后將編譯后的ConstTest.dll拷貝到Main.exe的bin文件夾下試試看),這時,只能添加ConstTest.dll引用,并且重新編譯Main程序才行。
聲明:本網頁內容旨在傳播知識,若有侵權等問題請及時與本網聯系,我們將在第一時間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com