虽然我们可以从基类/接口继承,但为什么我们不能声明List<>
使用相同的类/接口?
interface A
{ }
class B : A
{ }
class C : B
{ }
class Test
{
static void Main(string[] args)
{
A a = new C(); // OK
List<A> listOfA = new List<C>(); // compiler Error
}
}
Run Code Online (Sandbox Code Playgroud)
有办法吗?
我确信这个问题可以解决上一个问题中提出的问题,但我无法找到它.
C#类中有一个方法,它将基类的通用List作为参数.我需要传递一个继承类的列表,并且不知道如何执行此操作.我的尝试中出错了.以下是示例代码:
public class A
{
public static void MethodC(List<A>)
{
// Do Something here with the list
}
}
public Class B : A
{
// B inherits from A, A is the Base Class
}
// Code utilizing the above method
List<B> listOfB = new List<B>();
A.MethodC( (List<A>) listOfB ); // Error: this does not work
A.MethodC( listOfB.ToList<typeof(A)>() ); // Error: this does not work
A.MethodC( listOfB.ConvertAll<A>(typeof(A)) ); // Error: this does not work
// how can I …Run Code Online (Sandbox Code Playgroud)