简体   繁体   English

实现接口B的接口D的列表无法识别为列表

[英]List of interface D that implements interface B Can't be recognized as List<B>

I have an interface ID, which is derived from another interface IB. 我有一个接口ID,它是从另一个接口IB派生的。

public interface IB
{
    int Num { get; }
}

public interface ID : IB
{

}

Let's say we have a class that implements ID: 假设我们有一个实现ID的类:

public class DImpl : ID
{
     public int Num { get; set; }
}

I know that I can call a function that receives IB with a variable that is held as ID. 我知道我可以调用一个函数,该函数接收具有作为ID保留的变量的IB。

public void FuncOfIB(IB b)
{
     // do something
}

public static void Main()
{
     ID d = new DImpl();
     FuncOfIB(d); // Works
}

I would like to call a function that receives a List<IB> as a parameter: 我想调用一个接收List<IB>作为参数的函数:

void ProcessListOfIB(List<IB> list)
{
   // Some code
}

But it seems that I can't call this function with List<ID> . 但是似乎我无法使用List<ID>调用此函数。

public static void Main()
{
     List<ID> listID = new List<ID>();
     ProcessListOfIB(listID); // Doesn't work
}

Does anyone know why? 有人知道为什么吗? And how can I fix it? 我该如何解决? thank you. 谢谢。

Edit: I need the function ProcessListOfIB to remove an item from the list, so copying doesn't solve my problem... 编辑:我需要功能ProcessListOfIB从列表中删除一个项目,所以复制不能解决我的问题...

You can create Generic method and limit type to IB: 您可以创建通用方法并将类型限制为IB:

void ProcessListOfIB<T>(List<T> list) where T:IB
{
    // Some code
}

If you only need to loop through the collection (as opposed to modify it): 如果您只需要遍历集合(而不是修改它):

void ProcessListOfIB(IEnumerable<IB> list)
{
    // Some code
}

List既未标记为协变也不是协变的(因为它不可能是,它不是接口),所以这就是为什么它不起作用的原因。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 通用方法,其中 T 是实现接口的列表 - Generic Method where T is List that implements interface 无法在C#中将实现接口的类的实例添加到所述接口的List中 - Can't add instance of class that implements an interface to a List of said interface in C# C#表示A不是B的实例,但A实现了接口B. - C# says that A is not an instance of B yet A implements interface B 如何创建一个 List(of T),其中 T 是 (T) 的接口,List 的内容继承了一个实现 T 接口的抽象类 - How can I create a List(of T) where T is an interface of (T) and the contents of the List inherit an Abstract class that implements the interface of T 将B添加到列表 <A<object> &gt;,其中B用值类型实现A - Add B to List<A<object>>, where B implements A with a value type 具有实现接口的特定类的列表 - Having a list of a certain class that implements an interface 实现特定接口的“类型”的C#列表 - C# list of “Type” that implements specific interface <I>给定A的实例(A源自B且B实现I),</i>如何创建<I>包含B实例的</i>列表<I>?</i> - How to create a List<I> containing instances of B, given instances of A (A derives from B and B implements I)? 清单 <T> 作为接口上的属性 - List<T> as a property on an interface 演员表<t>列出<interface></interface></t> - Cast List<T> to List<Interface>
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM