![](/img/trans.png)
[英]How to set the value of a read-only property with generic getters and setters?
[英]“Read-only” public properties without setters/getters
C#是否具有这样的功能(例如Python的仅吸气剂模式)?
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方法...可以避免吗?
是的,这是可能的,语法如下:
public int AProperty { get; private set; }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.