C#:如何有效地引入“默认不可变”到 C#?不可变属性?
最近阅读 F# 和 C#,最大的区别之一是,F# 变体默认是不可变的,大多数 C# 引用类型默认是可变的。
这就带来了一个问题,如何高效地将这种“默认不可变”引入到 C# 编码中?呃...我的意思是C# 4.0..
我想到的是“不可变属性”。 因此,当它通过 Aspect 停靠到类时,会检查该类的每个成员,以便它们仅在构造函数中可变。
你觉得怎么样?
Reading F# and C# these days, one of the big difference is, F# variants are by default Immutable, most C# reference types are by default mutable.
This brings to a question, how to efficiently introduce this "Immutable as by default" to C# coding? er... i mean C# 4.0..
What came to my mind is an "Immutable Attribute".
So when this is docked to a class, by Aspect, each and every member of the class is checked, so that they are only mutable in constructors.
How do you think?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
readonly
关键字是一种语言级构造,用于执行您所请求的操作。当应用于成员变量时,它们只能在构造函数中设置,并且必须在构造函数中设置。The
readonly
keyword is a language-level construct to perform the very action you're requesting. When applied to member variables, they can only be set in the constructor and must be set in the constructor.我不熟悉 F#,但 C# 确实有一个只读关键字,只能应用于在对象创建时初始化的成员:
该关键字只能应用于不可变的成员,这意味着没有机制可以从外部更改它们班级。
I'm not familiar with F#, but C# does have a readonly keyword that can only be applied to members that are initialized at object creation:
The keyword can only be applied to members that are immutable, meaning there's no mechanism to alter them from outside the class.
我不完全确定您想要完成什么 - 无论您是在建议 C# 的新功能,还是在询问如何强制私有变量在构造期间之外都是不可变的。
如果是后者,您可以通过在声明私有变量时将其设置为只读来实现这一点。默认情况下,您无法将声明的每个变量设置为“只读”,因此您始终必须指定此关键字,但在编写新代码时遵循一些纪律,就可以完成工作。
还有一件事需要注意:不可变的变量与其指向的不可变对象不同。
例如,
I'm not entirely sure what you're trying to accomplish -- whether you're suggesting a new feature for C# or if you're asking how to implement forcing private variables to be immutable except during construction.
If it's the latter, you could accomplish that by making your private variables
readonly
when you declare them. You can't make every variable you declare "read only" by default, so you'll always have to specify this keyword, but with a bit of discipline when writing new code, it'd get the job done.One more thing to note: a variable being immutable isn't the same as the object it points to being immutable.
For example,