在依赖注入方面显式实现接口是否有好处?
据我了解,接口可以显式或隐式实现:
interface IFoo
{
void Bar();
}
//implicit implementation
class Foo1 : IFoo
{
public void Bar(){}
}
//explicit implementation
class Foo2 : IFoo
{
void IFoo.Bar(){}
}
现在显式实现只能通过调用接口方法来调用,而隐式实现可以直接在类的实例上调用:
class Baz
{
void Ba()
{
Foo1 foo1 = new Foo1();
foo1.Bar();
Foo2 foo2 = new Foo2();
foo2.Bar(); //syntax error
IFoo foo2_explicit = new Foo2();
foo2_explicit.Bar();
}
}
因此,使用显式接口实现,不能意外调用具体类的方法,但必须调用接口方法。这是否会阻止紧密耦合的代码作为 DI 的一个目的,还是我在这里吠叫错误的树?毕竟,不能意外地编写一个构造函数或方法来注入一个具体的类而不是一个接口:
class Baz
{
void Ba(Foo2 foo)
{
foo.Bar(); //syntax error
}
void Bb(IFoo foo)
{
foo.Bar();
}
}