C#是否具有这样的功能(比如Python的getter-only模式)?
class A
{
public [read-only] Int32 A_;
public A()
{
this.A_ = new Int32();
}
public A method1(Int32 param1)
{
this.A_ = param1;
return this;
}
}
class B
{
public B()
{
A inst = new A().method1(123);
Int32 number = A.A_; // okay
A.A_ = 456; // should throw a compiler exception
}
}
为了获得这个,我可以在A_属性上使用private修饰符,并且只实现一个getter方法。这样做,为了访问该属性,我应该总是调用getter方法......是否可以避免?
答案 0 :(得分:2)
是的,这是可能的,语法是这样的:
public int AProperty { get; private set; }
答案 1 :(得分:1)