C# 如何创建泛型类?
我怎样才能使这个通用?
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;
}
}
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;
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您需要 约束
T
成为引用类型,如下所示:编辑:我建议您还用属性替换方法:
You need to constrain
T
to be a reference type, like this:EDIT: I would recommend that you also replace the methods with a property:
我家里没有安装 VS 2005 来帮助调试您的解决方案,但我认为您需要限制 T。以下是一些可以提供帮助的资源:
泛型 C#
泛型解释(.NET Framework 版本 2.0)
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:
Generics C#
Generics Explained (.NET Framework version 2.0)