namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine(Web.WebsiteURL);
Web web = new Web();
Console.WriteLine(web.version);
}
}
class Web
{
// 常量
public const string WebsiteURL = "http://www.baidu.com";
// 隻讀字段
public readonly string version = "1.0.0";
}
}
- 常量隸屬于類,而不是對象,即沒有"執行個體常量"
- "執行個體常量"的角色由隻讀執行個體字段擔當
各種隻讀的應用常見
- 為了提高程式可讀性和執行效率 ==> 常量
- 為了防止對象的值被改變 ==> 隻讀字段
- 向外暴露不允許修改的資料 ==> 隻讀屬性(靜态或非靜态), 功能與常量有一些重疊
- 當希望成為常量的值其類型不能被常量聲明接收時(類/自定義結構體) ==> 靜态隻讀字段 (這句話太繞了)
class Web
{
public const string WebsiteURL = "http://www.baidu.com";
public readonly string version = "1.0.0";
// 錯誤,因為常量隻能接收基本類型資料
//public const Building Location = new Building("gz");
// 正确
public static readonly Building Location = new Building("gz");
}
class Building
{
public string Address { get; set; }
public Building(string address)
{
this.Address = address;
}
}