[英]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.