C# 接口与类:定义方法

C# 接口与类:定义方法,c#,class,oop,methods,interface,C#,Class,Oop,Methods,Interface,我对OO编程有点陌生,我试图理解这种实践的所有方面:继承、多态等等,但有一件事我的大脑不想完全理解:接口 我可以理解使用接口而不是类继承的好处(主要是因为一个类不能从多个父类继承),但我遇到了以下问题: 假设我有这样的东西: /** a bunch of interfaces **/ public interface IMoveable { void MoveMethod(); } public interface IKilleable() { void KillMethod(

我对OO编程有点陌生,我试图理解这种实践的所有方面:继承、多态等等,但有一件事我的大脑不想完全理解:接口

我可以理解使用接口而不是类继承的好处(主要是因为一个类不能从多个父类继承),但我遇到了以下问题:

假设我有这样的东西:

/** a bunch of interfaces **/
public interface IMoveable
{
    void MoveMethod();
}

public interface IKilleable()
{
    void KillMethod();
}

public interface IRenderable()
{
    void RenderMethod();
}

/** and the classes that implement them **/
public class ClassOne : IMoveable
{
    public void MoveMethod() { ... }
}

public class ClassTwo: IMoveable, IKilleable
{
    public void MoveMethod() { ... }
    public void KillMethod() { ... }
}

public class ClassThree: IMoveable, IRenderable
{
    public void MoveMethod() { ... }
    public void RenderMethod() { ... }
}

public class ClassFour: IMoveable, IKilleable, IRenderable
{
    public void MoveMethod() { ... }
    public void KillMethod() { ... }
    public void RenderMethod() { ... }
}
通过在这里使用接口,我必须在每个类中每次声明
MoveMethod
KillMethod
RenderMethod
。。。这意味着复制我的代码。一定是出了什么问题,因为我觉得这不太实际


那么我应该只在几个类上实现接口吗?或者我应该找到一种混合继承和接口的方法吗?

接口就像是类的契约。。如果某个类声明它支持这样一个接口,那么它必须按照您正确采样的方式定义它的方法。接口非常适合公开不容易跨不同类实现的公共内容

现在,从您的示例中,您最好结合使用一个类和一个接口的子类来防止重复代码。因此,您可以获得父结构代码常量,并根据需要进行扩展

/** Based on same interfaces originally provided... and the classes that implement them **/
public class ClassOne : IMoveable
{
    public void MoveMethod() { ... }
}

public class ClassTwo: ClassOne, IKilleable
{
    // Move Method is inherited from ClassOne, THEN you have added IKilleable
    public void KillMethod() { ... }
}

public class ClassThree: ClassOne, IRenderable
{
    // Similar inherits the MoveMethod, but adds renderable
    public void RenderMethod() { ... }
}

public class ClassFour: ClassTwo, IRenderable
{
    // Retains inheritance of Move/Kill, but need to add renderable
    public void RenderMethod() { ... }
}

可能最好的理解方法是编写单元测试,仅当您将标志传递给
格式化硬盘驱动器(bool really)
时,才验证格式化硬盘驱动器之前显示的对话框。实现这样的方法(不必实际销毁硬盘,但类似的方法)并尝试编写测试。这是一个很好的例子liked@Jonesy谢谢,真的很有帮助!这正是我想要的,谢谢你!:)