参考实现多个接口的类实例的正确方法是什么?
参考实现多个接口的类实例的正确方法是什么?
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");
}
}
如果我想将打印机类的实例作为依赖项,则可以使用IPRINTER接口进行依赖项注入。
如果我想将扫描仪类的实例作为依赖项,那么我可以将ISCanner接口用于依赖项注入。
现在,如果我想将ScannerPrinter类的实例作为依赖项,那么我应该使用哪个接口进行依赖项注入?
因为如果我使用iPrinter注入scannerprinter对象,那么我将无法访问扫描方法(scannerprinterobj.scan()将无效,因为它在isCanner中定义),反之亦然。
解决这个问题的正确方法应该是什么?
我的猜测是,我们需要创建另一个界面,例如 iDevice ,它将通过 iprinter 和 iscanner ,但是在这种情况下应该IDEVICE对print()和scan()方法都有声明,这将使实现iPrinter和Iscanner不必要,因为而不是实现iPrinter和isCanner,我可以直接在 scannerprinter 类上实现IDEVICE。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以定义
iprinterscanner
并使用它,如下所示:You can define
IPrinterScanner
and use that, as follows: