C#将扩展接口添加到列表中

时间:2016-09-27 08:57:06

标签: c# interface

我目前正在尝试将一组接口添加到另一个集合 - 问题是,我只想要扩展接口,而不是父接口。

让我详细说明:

interface IScanner
{
    void scan();
}

interface IPhotocopier : IScanner
{
     void Copy();
}

public class PrintingBusiness
{
    List<IPhotocopier> Photocopiers { get; set; }
}

public class ScannerBusiness
{
    List<IScanner> Scanners { get; set; }
}

public class Program
{   
      static void Main(string[] args)
      {
            PrintingBusiness printerBusiness = new PrintingBusiness();
            printerBusiness.Photocopiers = new List<IPhotocopier>();
            printerBusiness.Photocopiers.Add(new HPPrinter());
            printerBusiness.Photocopiers.Add(new CanonPrinter())

            ScannerBusiness scannerBusiness = new ScannerBusiness();
            scannerBusiness.Scanners = new List<IScanner>();
            scannerBusiness.Scanners.Add(printerBusiness.Photocopiers); // Here i want to retreive all the IScanners from my Photocopiers collection, but i get an ArgumentError: Cannot Convert from List<IPhotocopier> to List<IScanner>. 

      }
}

我想从我的Photocopiers系列中访问IScanner接口的集合 - 我想我可以通过简单地将Photocopiers集合添加到我的Scanners集合来直接进行 - 但是我需要迭代每个Photocopier并转换为IScanner然后将它们添加到我的扫描仪集合中? :-)

1 个答案:

答案 0 :(得分:3)

您应该使用AddRange方法,因为它可以遍历Photocopiers列表并将所有这些项添加到Scanners列表中:

scannerBusiness.Scanners.AddRange(printerBusiness.Photocopiers);

您不需要进行任何转换,因为IPhotocopier个实例可以隐含地投放到IScanner

另外,不要忘记初始化您的列表。它们现在是null