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