简体   繁体   English

C#如何制作泛型类?

[英]C# How to make a generic class?

How can I make this generic? 我怎样才能使这个通用?

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

My failed attempt: 我失败的尝试:

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

You need to constrain T to be a reference type, like this: 您需要将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;
    }
}

EDIT : I would recommend that you also replace the methods with a property: 编辑 :我建议你也用属性替换方法:

public T Value {
    get { return _value; }
    set { while(_value == CompareAndSet(value)); }
}

I don't have VS 2005 installed at home to help debug your solution, but I think you need to constrain T. Here are some some resources to assist: 我没有在家安装VS 2005以帮助调试您的解决方案,但我认为您需要约束T.这里有一些资源可以帮助:

Generics C# 泛型C#

Generics Explained (.NET Framework version 2.0) 泛型说明(.NET Framework 2.0版)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM