[英]Readonly property vs. readonly member variable in C#
I have a class ExProperty
something like below: 我有一个类
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);
}
}
What is the sole purpose of making/using a property readonly or write only? 只读或只写一个属性的唯一目的是什么? I see, through the following program that
readonly
achieves the same purpose! 我看到,通过以下程序,
readonly
达到了同样的目的!
When I make the property read-only, I think it should not be writable. 当我将属性设为只读时,我认为它不应该是可写的。 When I use
我用的时候
public void Asimplemethod() { _s=3; //Compiler reports as "Read only field cannot be used as assignment" System.Console.WriteLine(m_asimplevar); }
Yes, this is ok. 是的,这没关系。
But, If i use 但是,如果我使用
public ExProperty(int iTemp) { _s = 3 ; //compiler reports no error. May be read-only does not apply to constructors functions ? }
Why does the compiler report no error in this case ? 为什么编译器在这种情况下报告没有错误?
Is declaring _s=3
ok? 声明
_s=3
好吗? Or should I declare _s
and assign its value using a constructor? 或者我应该声明
_s
并使用构造函数赋值?
Yes, the readonly
keyword means that the field can be written to only in a field initializer and in constructors. 是的,
readonly
关键字意味着该字段只能在字段初始值设定项和构造函数中写入。
If you want, you can combine readonly
with the property approach. 如果您愿意,可以将
readonly
与属性方法结合使用。 The private
backing field for the property can be declared readonly
while the property itself has only a getter. 属性的
private
支持字段可以readonly
声明,而属性本身只有一个getter。 Then the backing field can be assigned to only in constructors (and in its possible field initializer). 然后,可以仅在构造函数(以及其可能的字段初始值设定项)中分配支持字段。
Another thing you could consider is making a public
readonly
field. 您可以考虑的另一件事是建立
public
readonly
字段。 Since the field itself is read-only, you actually don't achieve much from the getter if all it does is returning the field value. 由于字段本身是只读的,如果它只是返回字段值,你实际上并没有从getter获得太多。
Key point of properties is to provide interface for outside of the class. 属性的关键点是为类外提供接口。 By not defining
Set
or by making it private, you make it "read-only" for outside of the class, but it can still be changed from inside of the class methods. 通过不定义
Set
或将其Set
私有,您可以将其Set
为类外部的“只读”,但仍可以从类方法内部进行更改。
By making field readonly
, you are saying it should never change, no matter from where this change comes. 通过
readonly
字段,你说它永远不会改变,无论这种变化来自哪里。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.