主頁 > 知識(shí)庫 > .NET 中的 常量字段const應(yīng)用介紹

.NET 中的 常量字段const應(yīng)用介紹

熱門標(biāo)簽:銀行業(yè)務(wù) 電子圍欄 Linux服務(wù)器 Mysql連接數(shù)設(shè)置 團(tuán)購(gòu)網(wǎng)站 阿里云 科大訊飛語音識(shí)別系統(tǒng) 服務(wù)器配置

C#中,當(dāng)使用常數(shù)符號(hào)const時(shí),編譯器首先從定義常數(shù)的模塊的元數(shù)據(jù)中找出該符號(hào),并直接取出常數(shù)的值,然后將之嵌入到編譯后產(chǎn)生的IL代碼中,所以常數(shù)在運(yùn)行時(shí)不需要分配任何內(nèi)存,當(dāng)然也就無法獲取常數(shù)的地址,也無法使用引用了。

如下代碼:

復(fù)制代碼 代碼如下:

public class ConstTest
{
public const int ConstInt = 1000;
}

將其編譯成ConstTest.dll文件,并在如下代碼中引用此ConstTest.dll文件。
復(fù)制代碼 代碼如下:

using System;
class Program
{
public static void Main(string[] args)
{
Console.WriteLine(ConstTest.ConstInt);//結(jié)果輸出為1000;
}
}

編譯運(yùn)行此Main.exe程序,結(jié)果輸出為1000。之后將bin文件夾中的ConstTest.dll引用文件刪除,直接運(yùn)行Main.exe文件,程序運(yùn)行正常,結(jié)果輸出1000。

如果將ConstTest重新定義為:
復(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;
}
}

重新編譯成ConstTest.dll并向調(diào)用程序Main添加此引用后,再編譯調(diào)用程序,生成新的Main.exe,即使再次刪除ConstTest.dll文件后,Main.exe運(yùn)行正常,結(jié)果輸出1000。

將Main程序更改如下:
復(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
}
}

重新編譯Main程序,如果此時(shí)再把ConstTest.dll刪除,則會(huì)報(bào)錯(cuò)。

如此可以看出,如果某些工程引用到了ConstTest.dll,如果后來因?yàn)樽儎?dòng),改變了ConstInt常量的值,即使引用重新編譯的ConstTest.dll,也無法更改Main.exe中的數(shù)據(jù)(可以把ConstInt值改為其它值,然后將編譯后的ConstTest.dll拷貝到Main.exe的bin文件夾下試試看),這時(shí),只能添加ConstTest.dll引用,并且重新編譯Main程序才行。

標(biāo)簽:大理 萍鄉(xiāng) 棗莊 江蘇 衢州 衡水 廣元 蚌埠

巨人網(wǎng)絡(luò)通訊聲明:本文標(biāo)題《.NET 中的 常量字段const應(yīng)用介紹》,本文關(guān)鍵詞  ;如發(fā)現(xiàn)本文內(nèi)容存在版權(quán)問題,煩請(qǐng)?zhí)峁┫嚓P(guān)信息告之我們,我們將及時(shí)溝通與處理。本站內(nèi)容系統(tǒng)采集于網(wǎng)絡(luò),涉及言論、版權(quán)與本站無關(guān)。
  • 相關(guān)文章
  • 收縮
    • 微信客服
    • 微信二維碼
    • 電話咨詢

    • 400-1100-266