我想我在这里有一个非常天真的问题,我之前不知道甚至可能.请原谅我,如果我的标题问题有点模糊,因为我甚至不知道如何描述它.这段代码对我来说很奇怪.
public interface IMyInterface
{
void ImplementMe();
}
public class StandAlone
{
public void ImplementMe()
{
Console.writeline("It works!");
}
}
public class SubClass : StandAlone, IMyInterface
{
// no need to implement IMyInterface here but it still work!!!
}
IMyInterface myInterface = new SubClass();
myInterface.ImplementMe(); // Output : "It works!"
Run Code Online (Sandbox Code Playgroud)
我只想知道以下内容:
好吧,我想到的第一种情况 - 当你没有StandAlone类的源代码时,后来你决定引入描述StandAlone类行为的接口.例如,对于单元测试(不是最好的做法是模拟你不拥有的代码,但有时它可能会有帮助),或者你想StandAlone在某些情况下提供替代的行为实现.所以要么你没有选择对这些代码进行单元测试:
public class SUT
{
private readonly StandAlone dependency;
public SUT(StandAlone dependency)
{
this.dependency = dependency;
}
// ...
}
Run Code Online (Sandbox Code Playgroud)
但是,如果您将介绍接口,您实际上可以切换到依赖IMyInterface而不是StandAlone.并提供SubClass零接口的实现.
public class SUT
{
private readonly IMyInterface dependency;
public SUT(IMyInterface dependency)
{
this.dependency = dependency;
}
// ...
}
Run Code Online (Sandbox Code Playgroud)