const與readonly定義的值都不能更改,但它們到底有哪些異同點呢?
Const
² Const是常量的意思,其定義的變量只能讀取不能更改,且只能在定義時初始化,不能在構造函數與其它屬性與方法中初始化
public class ConstTest
{
/// <summary>
/// const定義的變量
/// </summary>
public const int SUM = 100;
public ConstTest()
{
//錯誤!const定義的變量不能在構造函數中初始化
SUM = 100;
}
public void method()
{
//錯誤!const定義的變量不能在方法中初始化
SUM = 100;
}
}
² Const 定義的字段屬於類訪問,類似於靜態變量,只能通過類名來訪問
//只能通過類名訪問
Console.WriteLine(ConstTest.SUM);
ConstTest t = new ConstTest();
//錯誤!無法通過實例對象訪問
Console.WriteLine(t.SUM);
² Const 只能定義值類型與字串,若定義引用類型的變量,只能初始化為null
/// <summary>
/// const定義的變量
/// </summary>
public const int SUM = 100;
public const string CHARACTER_STRING = "We are chinese!我們都是中國人!";
/// <summary>
/// const定義的引用類型只能初始化為null
/// </summary>
public const Object obj = null;
/// <summary>
/// 錯誤!const定義的引用類型只能初始化為null
/// </summary>
public const Person person = new Person();
readonly
readonly是只讀的意思,其定義的變量在運行期間也只能讀取不能更改,但與const有以下不同
readonly分為實例只讀變量與靜態只讀變量
² 實例只讀變量在定義時或者實例構造函數中初始化,通過對象訪問
public class ReadOnlyTest
{
/// <summary>
/// 定義時初始化(實例只讀變量)
/// </summary>
public readonly int sum = 0;
public ReadOnlyTest()
{
//實例只讀變量在實例構造函數中初始化
sum = 100;
}
}
客戶端訪問形式
ReadOnlyTest test = new ReadOnlyTest();
Console.WriteLine(test.sum);
² static readonly 靜態只讀變量可以在定義時或者靜態構造函數中初始化,通過類名稱訪問
public class ReadOnlyTest
{
/// <summary>
/// 定義時初始化(靜態只讀變量)
/// </summary>
public static readonly int static_sum = 0;
static ReadOnlyTest()
{
//靜態只讀變量在靜態構造函數中初始化
static_sum = 99;
}
}
客戶端訪問形式
Console.WriteLine(ReadOnlyTest.static_sum);
² 實例只讀變量若要在構造函數中初始化,只能選擇實例構造函數,靜態只讀變量若要在構造函數中初始化,只能選擇靜態構造函數
public class ReadOnlyTest
{
/// <summary>
/// 定義時初始化(實例只讀變量)
/// </summary>
public readonly int sum = 0;
/// <summary>
/// 定義時初始化(靜態只讀變量)
/// </summary>
public static readonly int static_sum = 0;
public ReadOnlyTest()
{
//錯誤!靜態只讀變量只能在靜態構造函數中初始化!
static_sum = 100;
}
static ReadOnlyTest()
{
//錯誤!實例只讀變量只能在實例構造函數中初始化!
sum = 100;
}
}
總結:
const與readonly相同點:運行期間都只能讀取不能更改
const 與readonly不同點:
1. const定義時即初始化,運行期間無法再初始化;readonly除了在定義時可以初始化外,還能在運行期間的構造函數中初始化,實例只讀變量只能在實例構造函數中初始化,靜態只讀變量只能在靜態構造函數中初始化
2. const定義的變量只能通過類名稱訪問,而readonly會根據其是否定義為靜態類型而分別通過對象與類名稱訪問
3. const只能定義值類型與字串,若定義引用類型則初始化值必須為null,而readonly無此限制,可以定義引用類型時初始化為null,在對應的構造函數中再重新初始化
=======================================
以上內容為個人原創,轉載請注明出處