readonly
readonly 的應用有四種型式
一、field declaration
對於已宣告 readonly 的欄位,建構式可以去重覆指定值,但方法則不允許。
using System;
class Example
{
static void Main(string[] args)
{
Console.WriteLine();
}
}
class Age
{
readonly int year;
Age(int year)
{
this.year = year;
}
void ChangeYear()
{
//year = 1967; // Compile error if uncommented.
}
}
readonly 可以指定 runtime constants 給他,const 則否。
public static readonly uint timeStamp = (uint)DateTime.Now.Ticks;
二、readonly struct definition
在 C# 7.2,當一個 struct 被宣告 readonly 時,其結構底下的所有 field 也必需一樣宣告 readonly。
public readonly struct Point
{
public readonly double X;
public readonly double Y;
}
當自動實作屬性只有 {get;} 時,則會被視為已宣告 readonly,
就不用特別再加 readonly 修飾詞了。
public readonly struct Point
{
public double X { get; }
public double Y { get; }
}
三、readonly member definition
在 C# 8.0,readonly 修飾詞可以用於 property 或 indexer。
using System;
class Example
{
static void Main(string[] args)
{
Console.WriteLine(new Point().Origin_two.X);
}
}
public readonly struct Point
{
public double X { get; }
public double Y { get; }
public Point(int x, int y)
{
X = x;
Y = y;
}
private static readonly Point origin = new Point(0, 0);
public readonly Point Origin_two
{
get
{
return origin;
}
}
}
readonly 修飾詞也可用於 get accessors。
using System;
class Example
{
static void Main(string[] args)
{
Console.WriteLine(new Point().Origin_two.X);
}
}
public readonly struct Point
{
public double X { get; }
public double Y { get; }
public Point(int x, int y)
{
X = x;
Y = y;
}
private static readonly Point origin = new Point(0, 0);
public Point Origin_two
{
readonly get
{
return origin;
}
set { Origin_two = value; }
}
}
但 readonly member 有其限制,
1、readonly 修飾詞不可用於 static methods or properties。
2、readonly 修飾詞不可用於建構式。
四、ref readonly method return
在 C# 7.2,readonly 修飾詞也可以跟 ref 修飾詞合用,需注意的是,
ref 修飾詞一定要在 readonly 修飾詞的前面。
using System;
class Example
{
static void Main(string[] args)
{
Console.WriteLine(Point.Origin_one().X);
}
}
public readonly struct Point
{
public double X { get; }
public double Y { get; }
public Point(int x, int y)
{
X = x;
Y = y;
}
private static readonly Point origin = new Point(0, 0);
public static ref readonly Point Origin_one()
{
return ref origin;
}
public static ref readonly Point Origin_two
{
get
{
return ref origin;
}
}
}
注意,當使用「ref readonly」修飾詞時,可以用於 static 方法,
不受於 readonly member 限制 (C# 8.0)。