如何在 C# 中运行时锁定/解锁字段?
我可以在运行时锁定/解锁字段或对象以防止写入吗?换句话说,比如在运行时将对象暂时更改为只读...
例如:
int x = 5; // x is 5
LockObject(x);
x = 7; // no change
UnlockObject(x);
x = 10; // x is 10
如果没有,您能给我一些可能的解决方案吗?
Can I lock/unlock fields or objects at runtime against writing? In other words something like changing objects to read-only temporarily at runtime...
For example:
int x = 5; // x is 5
LockObject(x);
x = 7; // no change
UnlockObject(x);
x = 10; // x is 10
if not can you give me some possible solutions?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以使用访问器来执行此操作...
You can use accessors to do this...
将其包装在属性中,然后使用布尔标志作为“锁”。
您还可以使用结构来处理此类逻辑。
示例客户端代码:
输出:
5
5
7
按任意键继续...
Wrap it in a property and then use a boolean flag as the "lock".
You can also use a struct to handle this type of logic.
Sample client code:
Output:
5
5
7
Press any key to continue...
感谢大家的帮助。这是一个更通用的替代方案。
我决定使用冻结/解冻会更方便,因为锁定/解锁存在于多线程编程的上下文中。
Thanks all for help. Here is a more generalized alternative.
I have decided that it would be more convenient to use freeze/unfreeze since lock/unlock exists in the context of multithreading programming.