如何使属性“一次写入多次读取”在 VB.NET 中?
使类属性“写入一次,读取多次”以便只能设置该属性一次的最佳方法是什么?
我知道我可以传递构造函数中的所有属性并使它们只读,但在有很多属性的情况下,我不想要一个具有 20 多个参数的构造函数。
另外,我意识到我可以“推出自己的”设置器,但必须为每个属性执行此操作似乎是一堆冗余编码。
在 VB 2008 .NET 3.5 中是否有一种干净的方法可以做到这一点?
What is the best way to make a class property "Write Once, Read Many" such that you can only set the property once?
I know that I could pass all the properties in the constructor and make them ReadOnly, but in cases with a lot of properties I don't want a constructor that has 20+ arguments.
Also, I realize I can "roll my own" setters, but having to do that for every property seems like a bunch of redundant coding.
Is there a clean way to do this in VB 2008 .NET 3.5?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
一次写入属性永远不会“干净”。
我建议创建一个构建器/工厂类以避免 20 参数 CTor。
(是的,我知道这是相当多的打字)
这里类似的讨论:
我应该使用一次设置变量吗?
[编辑]此外,即使您坚持认为,除了滚动您自己的设置器之外,我也看不到其他选择,这也需要大量输入。
A Write Once Property is never "clean".
I'd recommend to create a builder/factory class to avoid the 20 param CTor.
(Yes, I know it is quite some typing)
Similar discussion here:
Should I use set once variables?
[edit] Furthermore, even if you insist I don't see another option than rolling your own setters, which is a lot of typing, too.
我知道已经快三年了,但这是我认为更好的解决方案:
I know it's been almost 3 years, but here's my solution which I think is better:
“最干净”的方法是根本不这样做并使用自动属性。我也看不出有必要。它们只能被写入一次真的那么重要吗?如果是这样,我肯定会选择一个将所有属性的值作为参数的构造函数。
The "cleanest" way would be not to do it at all and use auto properties. I fail to see the need for it too. Is it really that important that they can only be written once? If so I would definitely go with a constructor that takes values for all the properties as parameters.