如何创建具有继承的泛型类?
如何使以下代码有效?我不认为我完全理解C#泛型。也许,有人可以指出我正确的方向。
How can I make the following code work? I don't think I quite understand C# generics. Perhaps, someone can point me in the right direction.
public abstract class A
{
}
public class B : A
{
}
public class C : A
{
}
public static List<C> GetCList()
{
return new List<C>();
}
static void Main(string[] args)
{
List<A> listA = new List<A>();
listA.Add(new B());
listA.Add(new C());
// Compiler cannot implicitly convert
List<A> listB = new List<B>();
// Compiler cannot implicitly convert
List<A> listC = GetCList();
// However, copying each element is fine
// It has something to do with generics (I think)
List<B> listD = new List<B>();
foreach (B b in listD)
{
listB.Add(b);
}
}
这可能是一个简单的答案。
It's probably a simple answer.
更新:
首先,这在C#3.0中是不可能的,但在C#4.0中是可能的。
Update: First, this is not possible in C# 3.0, but will be possible in C# 4.0.
要使它在C#3.0中运行,这只是一个解决方法,直到4.0,请使用以下内容:
To get it running in C# 3.0, which is just a workaround until 4.0, use the following:
// Compiler is happy
List<A> listB = new List<B>().OfType<A>().ToList();
// Compiler is happy
List<A> listC = GetCList().OfType<A>().ToList();
你总是可以这样做
List<A> testme = new List<B>().OfType<A>().ToList();
正如Bojan Resnik指出的那样,你也可以......
As "Bojan Resnik" pointed out, you could also do...
List<A> testme = new List<B>().Cast<A>().ToList();
值得注意的是,如果一个或多个类型,Cast< T>()将失败不匹配。其中OfType< T>()将返回IEnumerable< T>仅包含可转换的对象
A difference to note is that Cast<T>() will fail if one or more of the types does not match. Where OfType<T>() will return an IEnumerable<T> containing only the objects that are convertible