如何为抽象类中的只读字段赋值?
我在基本抽象类中有一个字段。我想将此字段设置为只读,以便在子类初始化后其值不会更改。
但抽象类不能有构造函数,只读只能从构造函数初始化。
如何实现这一目标?
I have a field in base abstract class. I want to make this field readonly so that its value do not changed after child class has been initialized.
But abstract class cannot have constructor and readonly can only be initialized from constructor.
How to achieve this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
例如,您可以从子类构造函数调用基类的构造函数,如下所示:
基类中的只读字段和构造函数:
子类中的构造函数:
You could for instance call a the constructor of your base class from the child class constructor like this:
Readonly field and constructor in base class:
Constructors in child class:
abstract
类可以有构造函数。如果我是你,我会拥有该字段非只读受保护字段,但将其公开为公共只读属性
abstract
class can have constructor.If I were you I would have the field not readonly protected field but expose it as public readonly property
抽象类可以有一个构造函数,但它们不能被初始化。
Abstract classes CAN have a constructor, they can simply not be initiated.