我想我错过了"编程到界面"的概念

pgh*_*ech 1 c# interface

所以我仍然是C#的新手,并且使用接口,当我认为我理解它们时,我意识到我并不完全.我发现我在寻求一些澄清的困惑是,当你创建一个接口,并有一个继承自它的类

public Interface ISomeInterface
{
  //some methods/properties
}

public class FooClass : ISomeInterface
{
  //implemented ISomeInterfaces methods/properties
}
Run Code Online (Sandbox Code Playgroud)

并且在程序中的某个实现中使用此类对象

public class BarClass 
{
  private ISomeInterface _someInterface;
  public BarClass(ISomeInterface someInterface)
  {
    _someInterface = someInterface;
  }
  //rest of class
}
Run Code Online (Sandbox Code Playgroud)

我的困惑是为什么我这样设置它.我以为我会实例化一个FooClass类型的新对象,并在构造函数中使用类型为FooClass的对象:

public class BarClass 
{
  private FooClass _fooClass;
  public BarClass(FooClass fooClass)
  {
    _fooClass = fooClass;
  }
  //rest of class
}
Run Code Online (Sandbox Code Playgroud)

理解这一点我错过了什么?我不认为我会直接声明接口的对象?

提前致谢.

Dar*_*rov 7

这个想法是BarClass不应该紧密耦合到特定的实现ISomeInterface.

如果你使用这个:

public BarClass(FooClass fooClass)
Run Code Online (Sandbox Code Playgroud)

这意味着BarClass只能使用这个特定的FooClass实现,而不能用于任何其他实现.如果您使用:

public BarClass(ISomeInterface fooClass)
Run Code Online (Sandbox Code Playgroud)

现在BarClass不再紧密耦合了FooClass.这意味着BarClass只要它遵守定义的合同(接口),现在可以传递他想要的接口的任何实现.因此,如果他想要FooClass传递一个实例FooClass,但如果他不满意,FooClass他可以编写自己的实现并将其传递给构造函数,并且从这个角度来看BarClass这是绝对透明的(不需要修改) ).

类之间的弱耦合是OOP最基本的方面之一,因为它允许您轻松地将一个组件替换为另一个组件,而无需重写整个应用程序.