我可以创建一个列表与LT; WeakReference的< T>> ;? [英] Can I create a List<WeakReference<T>>?
问题描述
我试图创建的WeakReference
的表S使用4.5通用的实施,使我能避免类型检查和的WeakReference铸造
目标。但是,的WeakReference< T>
似乎并不支持协方差,所以我试图建立一个解决方法。
I'm trying to create a List of WeakReference
s using the 4.5 generic implementation so that I can avoid type checking and casting of the WeakReference
target. But, WeakReference<T>
doesn't appear to support covariance, so I'm trying to establish a workaround.
我想它应该是可行的,因为每个T公司将在一个特定的继承链的类型。所以,我在想什么会沿着这些路线:
I'm thinking it should be doable since each T would be of a type in a particular inheritance chain. So, what I'm thinking would be along these lines:
public class Animal { }
public class Tiger : Animal { }
public class Wolf : Animal { }
var mylist = new List<WeakReference<Animal>>();
mylist.Add(new WeakReference<Animal>(new Animal()));
mylist.Add(new WeakReference<Tiger>(new Tiger()));
mylist.Add(new WeakReference<Wolf>(new Wolf()));
我试图创造WeakReference的(因为它是不遗传的)一个包装类,但没有按'T的工作。不管是什么,该列表将不超过接受任何类型的的WeakReference
等的WeakReference<动物方式>
我可以创建自己的通用的WeakReference
的实现,但似乎被击败,因为我会做类型转换点在其中。我找不到任何文件,但我有种假设框架版本处理这更好的。
I could create my own generic WeakReference
implementation, but that would seem to be defeating the point since I'd be doing type casting within it. I can't find any documentation, but I'm kind of assuming the framework version handles this better.
有没有办法,我没有想到处理这个法子的,还是我找错了树?
Is there another way of handling this that I'm not thinking of, or am I barking up the wrong tree?
推荐答案
的WeakReference
是不变的,因为它允许值被设置,并且将是无效的,如果它是协变。为了让协变的,你需要做一个只读围绕基准包装,并且还使用一个接口。
WeakReference
is invariant, since it allows the value to be set, and that wouldn't be valid if it were covariant. To make it covariant you'll need to make a read only wrapper around the reference, and also use an interface.
public interface IReadOnlyWeakReference<out T>
{
T Value { get; }
}
public class WeakReferenceWrapper<T> : IReadOnlyWeakReference<T>
where T : class
{
private WeakReference<T> reference;
public WeakReferenceWrapper(WeakReference<T> reference)
{
this.reference = reference;
}
public T Value
{
get
{
T output;
if (reference.TryGetTarget(out output))
return output;
else
return default(T);
}
}
}
有关转换的扩展方法也有些方便:
An extension method for the conversion is also somewhat convenient:
public static IReadOnlyWeakReference<T> AsReadOnly<T>(
this WeakReference<T> reference)
where T : class
{
return new WeakReferenceWrapper<T>(reference);
}
现在我们可以这样写:
var mylist = new List<IReadOnlyWeakReference<Animal>>();
mylist.Add(new WeakReference<Animal>(new Animal()).AsReadOnly());
mylist.Add(new WeakReference<Tiger>(new Tiger()).AsReadOnly());
mylist.Add(new WeakReference<Wolf>(new Wolf()).AsReadOnly());
这篇关于我可以创建一个列表与LT; WeakReference的< T>> ;?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!