创建具有多个只读属性的类的实例
创建和初始化具有多个只读属性的类的实例的优雅方法是什么?在构造函数中传递所有值并不是很方便。
目的是实例在初始化后是不可变的。但是,如果构造函数不用于初始化所有属性值,那么如何从另一个类更改只读属性呢?
What is an elegant way to create and initialise instances of a class that has several readonly properties? Passing all values in a constructor would not be very convenient.
The purpose is that instances are immutable after initialisation. However if the constructor is not used for initialising all the property values, then how can the readonly properties be changed from another class?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
它们是只读的,因此在构建后无法修改。此行为是设计使然。
如果您想减少参数数量,请查看参数对象模式
They are readonly so that they can't be modified after construction. This behavior is by design.
If you want to reduce the parameter count have a look at the Parameter Object Pattern
您有两种选择
创建一个公共子程序以在初始化后更新变量,或者将更新添加到类的私有方法中的另一部分代码。
您使用反射来更新私有变量值。
第一种方法是迄今为止最好的选择,秒是一个黑客。
You have two choices
Create a public sub to update the Variables after initialization, or add the update to another section of code within the private methods of the class.
You use reflection to update the private Variables value.
The 1st way is by far the best option, the seconds is a hack.