[英]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.