程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> ASP.NET >> ASP.NET基礎 >> .NET 中的 常量字段const應用介紹

.NET 中的 常量字段const應用介紹

編輯:ASP.NET基礎

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);//結果輸出為1000;
}
}

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

如果將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運行正常,結果輸出1000。

將Main程序更改如下:
復制代碼 代碼如下:
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程序,如果此時再把ConstTest.dll刪除,則會報錯。

如此可以看出,如果某些工程引用到了ConstTest.dll,如果後來因為變動,改變了ConstInt常量的值,即使引用重新編譯的ConstTest.dll,也無法更改Main.exe中的數據(可以把ConstInt值改為其它值,然後將編譯後的ConstTest.dll拷貝到Main.exe的bin文件夾下試試看),這時,只能添加ConstTest.dll引用,並且重新編譯Main程序才行。

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved