我怎么知道在我的界面中放什么?

时间:2013-10-06 20:02:33

标签: c# oop interface polymorphism

在尝试为我的程序设计逻辑时,我遇到了这个反复出现的问题。假设我有一个IDriveable接口。

interface IDriveable
{
  public void Drive();
}

然后是实现此(c#)语法的汽车类:

class Car : IDriveable
{
  public void Drive(){
  //Do the movement here.
  }

}

这是我的问题发生的地方。如果我正在设计游戏,那么汽车不会自行驾驶,玩家应该驾驶汽车,这当然有意义吗?

class player
{
    public void Drive(IDriveable vehicle){

        vehicle.Drive();
     }
}

感觉就像我在'ping-ponging'的逻辑似乎并不合适。

1 个答案:

答案 0 :(得分:0)

构建代码的更好方法可能是这样的:

class Player // Start class names with a capital letter
{
    Car thisPlayersCar; // Initialize it  the constructor or somewhere appropriate

    public void someFunction() {
        thisPlayersCar.Drive();
    }
}

基本上,界面的目的是无论你在thisPlayersCar.Drive();(或任何Drive()IDriveable)调用,都可以保证对象有Drive()功能准备就绪。

相关问题