【发布时间】:2015-01-05 14:24:13
【问题描述】:
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 方法......这是可以避免的吗?
【问题讨论】:
-
是的。您可以使用
get和set之一或两者定义属性,并带有支持字段。但是,这并不能阻止您在类内获得支持字段。自 C# 6 起,这已扩展到自动属性,向后 C# 5 中的自动属性始终能够更改 getter 或 setter 的可访问性,但不能省略其中之一。 -
太好了,谢谢亚当! (:
标签: c# oop properties readonly