ASP.NET中readonly與const的區(qū)別詳解
更新時間:2015年10月10日 11:28:26 投稿:lijiao
如果你學(xué)過ASP.NET理論知識都會知道,在ASP.NET中 readonly和const修飾的變量都是恒量,它們的值是不可以被修改的。但是他們之間到底有什么區(qū)別?下面小編就它們的區(qū)別用例子來進(jìn)行說明。
const是一個修飾常量的關(guān)鍵字,它限定一個變量不允許被改變。使用const在一定程度上可以提高程序的安全性和可靠性,它在程序設(shè)計中有著非常重要的作用,給開發(fā)人員帶來非常方便的應(yīng)用。
下面我們來建一個控制臺應(yīng)用程序作測試:
public class Test
{
public readonly string name = "George";
public const string coname = "ABC Company LLC";
public Test(string name)
{
// readonly 修飾的變量能且只能在 Constructor(構(gòu)造函數(shù))中被改變
this.name = name;
}
public string _name
{
get
{
return name;
}
//不可以對readonly修飾的變量進(jìn)行Set操作
//set
//{
// name = value;
//}
}
}
class Program
{
static void Main(string[] args)
{
Test obj = new Test("Test");
//readonly的變量不可以修改值,只能在 Constructor(構(gòu)造函數(shù))中被改變
//obj.name = "New Value";
Console.WriteLine(obj.name);
//const 的變量直接通過對象訪問,不需要實例化
Console.WriteLine(Test.coname);
Console.Read();
}
}
以前一直以為 readonly 與 const 的作用是一樣的,現(xiàn)在明白它們之間的區(qū)別了,不知道您是否也明白了呢?希望大家有所收獲吧!
相關(guān)文章
.Net Core3 用Windows 桌面應(yīng)用開發(fā)Asp.Net Core網(wǎng)站
這篇文章主要介紹了.Net Core3 用Windows 桌面應(yīng)用開發(fā)Asp.Net Core網(wǎng)站,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-01-01

