[英]Readonly property vs. readonly member variable in C#
我有一個類ExProperty
,如下所示:
class ExProperty
{
private int m_asimplevar;
private readonly int _s=2;
public ExProperty(int iTemp)
{
m_asimplevar = iTemp;
}
public void Asimplemethod()
{
System.Console.WriteLine(m_asimplevar);
}
public int Property
{
get {return m_asimplevar ;}
//since there is no set, this property is just made readonly.
}
}
class Program
{
static void Main(string[] args)
{
var ap = new ExProperty(2);
Console.WriteLine(ap.Property);
}
}
只讀或只寫一個屬性的唯一目的是什么? 我看到,通過以下程序, readonly
達到了同樣的目的!
當我將屬性設為只讀時,我認為它不應該是可寫的。 我用的時候
public void Asimplemethod() { _s=3; //Compiler reports as "Read only field cannot be used as assignment" System.Console.WriteLine(m_asimplevar); }
是的,這沒關系。
但是,如果我使用
public ExProperty(int iTemp) { _s = 3 ; //compiler reports no error. May be read-only does not apply to constructors functions ? }
為什么編譯器在這種情況下報告沒有錯誤?
聲明_s=3
好嗎? 或者我應該聲明_s
並使用構造函數賦值?
是的, readonly
關鍵字意味着該字段只能在字段初始值設定項和構造函數中寫入。
如果您願意,可以將readonly
與屬性方法結合使用。 屬性的private
支持字段可以readonly
聲明,而屬性本身只有一個getter。 然后,可以僅在構造函數(以及其可能的字段初始值設定項)中分配支持字段。
您可以考慮的另一件事是建立public
readonly
字段。 由於字段本身是只讀的,如果它只是返回字段值,你實際上並沒有從getter獲得太多。
屬性的關鍵點是為類外提供接口。 通過不定義Set
或將其Set
私有,您可以將其Set
為類外部的“只讀”,但仍可以從類方法內部進行更改。
通過readonly
字段,你說它永遠不會改變,無論這種變化來自哪里。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.