我有一个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
使用构造函数声明并分配它的值?