简体   繁体   中英

What is the correct way to reference instance of class that implements multiple interfaces?

What is the correct way to reference an instance of a class which implements multiple interfaces?

public interface IPrinter {
  public void Print();
}

public interface IScanner {
  public void Scan();
}

public class ScannerPrinter : IPrinter, IScanner{
  public void Print() {
    Console.WriteLine("I can print");
  }
  public void Scan() {
    Console.WriteLine("I can scan");
  }
}

public class Printer : IPrinter {
  public void Print() {
    Console.WriteLine("I can only print");
  }
}

public class Scanner : IScanner {
  public void Scan() {
    Console.WriteLine("I can only scan");
  }
}

If I want to pass an instance of Printer class as a dependency then I can use IPrinter interface for dependency injection.

If I want to pass an instance of Scanner class as a dependency then I can use IScanner interface for dependency injection.

Now if I want to pass an instance of ScannerPrinter class as a dependency then which interface should I use for dependency injection??

Because if I use IPrinter for injecting ScannerPrinter object then I will not have access to scan method (scannerPrinterObj.Scan() will be invalid as it is defined in IScanner) and vice versa.

What should be the correct approach to solve this?

My guess is that we would require to create another interface something like IDevice which will be extended by IPrinter and IScanner , but in that case IDevice should have declaration for both Print() and Scan() method which will make implementing IPrinter and IScanner unnecessary as instead of implementing both IPrinter and IScanner I can directly implement IDevice on ScannerPrinter class.

You can define IPrinterScanner and use that, as follows:

public interface IPrinterScanner : IPrinter, IScanner
{
  // nothing to add (for now)
}

public class ScannerPrinter : IScannerPrinter
{
  public void Print() {
    Console.WriteLine("I can print");
  }
  public void Scan() {
    Console.WriteLine("I can scan");
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM