【发布时间】:2019-12-24 22:52:21
【问题描述】:
我有一个实现接口的类。第二个类实现了第一个类的 IList。我需要将第二个类分配给一个通用属性,它是接口的 IList。
这是我使用的代码的演示:
public class SODemo
{
public SODemo()
{
ClassWithIListOfClassWithInterface classWithIList = new ClassWithIListOfClassWithInterface();
IList<IDemoInterface> listOfInterfaces;
// CS0266: Cannot implicitly convert type ...
listOfInterfaces = classWithIList;
}
}
public class ClassWithInterface : IDemoInterface
{
// ...
}
public class ClassWithIListOfClassWithInterface : IList<ClassWithInterface>
{
// ...
}
从类似问题的答案中,我发现它似乎根本不起作用。
我为什么需要这个?
我有很多像ClassWithIListOfClassWithInterface 这样实现的类,我需要一个通用的处理程序。
问题:
我的目标是通过接口中实现的方法访问listOfInterfaces中的每个元素。
我可以使用任何替代方法吗?
编辑
这个我已经试过了
listOfInterfaces = (IList<IDemoInterface>)classWithIList;
然后我在运行时收到System.InvalidCastException。
【问题讨论】:
-
局部变量可以用
IEnumerable代替ILIst吗? -
@DStanley 不,我需要 Add() Remove() ... 东西,出于性能原因,我需要 List()
-
那么你不能使用更通用的变量。基础列表将更加具体,并可能导致运行时错误(例如,尝试将
ClassWithInterface2添加到List<ClassWithInterface>)。变量类型只是告诉编译器允许对底层对象进行哪些操作。 -
@DStanley 感谢您的提示。这听起来令人不安。你有具体的例子吗?
-
我不确定你的意思 -
List<Banana>不是IList<Fruit>,因为你不能向它添加Apple。因此,在您的情况下,您不能使用更通用的变量来引用更具体的集合。
标签: c# inheritance interface