C# 3.0 对象初始化 - 是否有对象正在初始化的通知?
我们有几个域对象需要支持只读和读写模式;它们目前有一个用于此目的的 bool Locked
属性 - 当 Locked
尝试更改对象的属性时,会导致 InvalidOperationException
。对象的默认状态是锁定。
C# 3 的对象初始化语法引入了一个小问题,即对象必须在初始化期间解锁(或默认解锁),然后在最后显式锁定。
使用 C# 3 的对象初始化语法时,是否有一种方法可以接收对象正在初始化或初始化已完成的通知? System.ComponentModel.ISupportInitialize
是我最大的希望,但它没有被调用。
We have several domain objects which need to support both read-only and read-write modes; they currently have a bool Locked
property for this--when Locked
attempts to alter properties on the object result in an InvalidOperationException
. The default state for the objects is Locked.
The object-initialization syntax of C# 3 introduces a small issue with these, in that the object must be unlocked (or default to be unlocked) during initialization and then locked explicityly at the end.
When using C# 3's object initialization syntax is there a means of receiving notification that the object is being intitialized or that initialization is complete? System.ComponentModel.ISupportInitialize
was my best hope, but it doesn't get called.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以使用流畅的 API 并附加它:
其中
Freeze
方法返回相同的实例(流畅) - 类似于:(如果需要,您可以更加集中检查)
You could use a fluent API and append it:
where the
Freeze
method returns the same instance (fluent) - something like:(you could centralize the check a bit more if needed)
不,没有这样的通知机制。对象初始值设定项功能将简单地调用指定的构造函数,然后按照列出的顺序设置可访问的字段/属性。没有可用的界面支持此功能的通知。
No, there is no such notification mechanism. The object initializer feature will simply call the specified constructor and then set the accessible fields / properties in the order they are listed. There is no interface available which supports notifications for this feature.
不。对象初始值设定项只是一个编译器功能,可帮助初始化对象。他们直接调用属性。
您需要强制使用构造函数,或者添加“锁定”方法来显式锁定它们。
No. The object initializers just are a compiler feature to assist in initializing your objects. They call the properties directly.
You need to either force constructor usage, or add a "lock" method to lock them down explicitly.