我有一个类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 所做的只是返回字段值,您实际上不会从 getter 中获得太多成就。
属性的关键点是为类外部提供接口。通过不定义Set
或将其设为私有,可以使它在类外部"只读",但仍可以从类方法内部进行更改。
通过制作现场readonly
,你说它永远不应该改变,无论这种变化来自哪里。