C#如何保护原子类的字段?
我正在尝试在 C# 中创建一个 AtomicReference 类,并且我想保护字段引用,但我还需要在 get 方法中返回值:
class AtomicReference
{
private Object _value;
public AtomicReference()
{
_value = new Object();
}
public AtomicReference(Object value)
{
OptimisticSet(value);
}
public Object CompareAndSet(Object newValue)
{
return Interlocked.Exchange(ref _value, newValue);
}
public void OptimisticSet(Object newValue)
{
do {
} while (_value == Interlocked.CompareExchange(ref _value, _value, newValue));
}
public Object Get()
{
// Don't leak the field reference
const Object constVal = _value;
return constVal;
}
}
这是解决问题的有点笨拙的方法...我可以' t 使该字段只读,因为我需要能够设置它。有比我更好的解决方案吗?
更新: 感谢您的快速回复! 有人正确地指出,如果我简单地返回 _value,引用将受到保护。我还想保护 _value 免于变异。如果我允许 _value 在 AtomicReference 之外发生变异,那么它就违背了创建此类的整个目的......有没有办法实现这一点?
I'm trying to make an AtomicReference class in C# and I want to keep the field reference protected, but I also need to return the value in the get method:
class AtomicReference
{
private Object _value;
public AtomicReference()
{
_value = new Object();
}
public AtomicReference(Object value)
{
OptimisticSet(value);
}
public Object CompareAndSet(Object newValue)
{
return Interlocked.Exchange(ref _value, newValue);
}
public void OptimisticSet(Object newValue)
{
do {
} while (_value == Interlocked.CompareExchange(ref _value, _value, newValue));
}
public Object Get()
{
// Don't leak the field reference
const Object constVal = _value;
return constVal;
}
}
It's a bit of a clumsy way around the problem... I can't make the field readonly, because I need to be able to set it. Is there a better solution than mine?
UPDATE:
Thanks for the quick responses!
It was rightfully pointed out that the reference will be protected if I simply return _value. I also want to protect the _value from mutating. If I allow the _value to mutate outside of the AtomicReference, then it defeats the entire purpose of making this class... is there a way to achieve that?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
即使您尝试,也不可能返回对 C#(没有不安全代码)或 Java 中的字段的引用。 (我不是指对对象的引用)
您可以简单地编写
return _value;
您的调用者将无法写入该字段。Even if you try, it is not possible to return a reference to a field in C# (without unsafe code) or Java. (I don't mean a reference to an object)
You can simply write
return _value;
your callers will not be able to write to the field.C# 不支持 C++ 的
const
关键字,该关键字允许对可变对象进行不可变引用。只有两种方法可以满足您的要求。
C# does not support C++'s
const
keyword, which allows for immutable references to mutable objects.There are only two ways to do what you're asking.