相关疑难解决方法(0)

将List <DerivedClass>转换为List <BaseClass>

虽然我们可以从基类/接口继承,但为什么我们不能声明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# collections inheritance list covariance

162
推荐指数
7
解决办法
10万
查看次数

将基类型列表转换为继承类型列表

我确信这个问题可以解决上一个问题中提出的问题,但我无法找到它.

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)

c# generic-list

19
推荐指数
2
解决办法
2万
查看次数

标签 统计

c# ×2

collections ×1

covariance ×1

generic-list ×1

inheritance ×1

list ×1