C#如何制作泛型类?

时间:2009-12-02 03:03:40

标签: c# generics concurrency operator-overloading

如何制作此通用名称?

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;
    }
}

2 个答案:

答案 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.以下是一些可以提供帮助的资源:

Generics C#

Generics Explained (.NET Framework version 2.0)