如何制作此通用名称?
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()
{
return _value;
}
}
我失败的尝试:
class AtomicReference<T>
{
private T _value;
public AtomicReference()
{
}
public AtomicReference(T value)
{
Set(value);
}
public T CompareAndSet(T newValue)
{
// _value is not an object that can be referenced
return Interlocked.Exchange(ref _value, newValue);
}
public void OptimisticSet(T newValue)
{
// I can't use the operator== with type T
do{}while(_value == CompareAndSet(newValue));
}
public T Get()
{
return _value;
}
}
答案 0 :(得分:11)
您需要constrain T
作为参考类型,如下所示:
class AtomicReference<T> where T : class {
private T _value;
public AtomicReference() { }
public AtomicReference(T value) {
OptimisticSet(value);
}
public T CompareAndSet(T newValue) {
return Interlocked.Exchange(ref _value, newValue);
}
public void OptimisticSet(T newValue) {
while (_value == CompareAndSet(newValue));
}
public T Get() {
return _value;
}
}
编辑:我建议你也用属性替换方法:
public T Value {
get { return _value; }
set { while(_value == CompareAndSet(value)); }
}
答案 1 :(得分:0)
我没有在家安装VS 2005以帮助调试您的解决方案,但我认为您需要约束T.以下是一些可以提供帮助的资源: