2008-12-29 75 views
1

我想建立一个很好的API(C#),使人们更容易消耗,我想我以前见过这个,想知道如何做到这一点:如何实现这种类型的OOP结构?

MyNamespace.Cars car = null; 

if(someTestCondition) 
     car = new Honda(); 
else  
     car = new Toyota(); 

car.Drive(40); 

这可能吗?如果是这样,需要做些什么?

+0

我希望你不要期望这两款车都是基于这种奇异的汽车驾驶方式。变种名称必须与本田和丰田不同 – Bob 2008-12-29 21:55:38

+0

确定我更改了代码以使其更准确,谢谢。 – Blankman 2008-12-29 22:05:22

回答

10
Interface Car 
{ 
void Drive(int miles); 
} 

class Honda : Car 
{ 
... 
} 
class Toyota : Car 
{ 
... 
} 
+0

你打败了我。我会删除我的 – 2008-12-29 21:51:51

+0

,应该是接口ICar – foson 2008-12-29 21:54:24

1

创建一个名为Cars的类。给它的驱动器方法。在您的本田和丰田课堂上扩展该基础班级。

6

您可以通过几种不同的方法来实现这一点。你可以声明一个抽象基类,或者你可以有一个你的对象实现的接口。我相信“C#”首选的方法是有一个接口。喜欢的东西:

public interface ICar 
{ 
    public Color Color { get; set; } 

    void Drive(int speed); 
    void Stop(); 

} 

public class Honda : ICar 
{ 

    #region ICar Members 

    public Color Color { get; set; } 

    public void Drive(int speed) 
    { 
     throw new NotImplementedException(); 
    } 

    public void Stop() 
    { 
     throw new NotImplementedException(); 
    } 

    #endregion 
} 

public class Toyota : ICar 
{ 
    #region ICar Members 

    public Color Color { get; set; } 

    public void Drive(int speed) 
    { 
     throw new NotImplementedException(); 
    } 

    public void Stop() 
    { 
     throw new NotImplementedException(); 
    } 

    #endregion 
} 
0
namespace MyNameSpace 
{ 
    public interface Cars 
    { 
    public void Drive(int miles); 
    } 
    public class Honda : Cars 
    { 
    public void Drive(int miles) { ... } 
    } 
    public class Toyota : Cars 
    { 
    public void Drive(int miles) { ... } 
    } 
} 
0

不要忘了命名空间,也看到了有关变量名

namespace MyNamespace { 
    public interface Cars { 
     void Drive(int speed); 
    } 

    public class Honda : Cars { 
     public void Drive(int speed) { 
     } 
    } 
    public class Toyota : Cars { 
     public void Drive(int speed) { 

     } 
    } 
} 
0

做一个叫做汽车的抽象类与称为驱动抽象方法的问题,我的评论( )。将其子类化并添加实现。

5

我看到每个人都在向你推送接口/抽象基类的变化。您提供的伪代码或多或少意味着您已经拥有此代码。

我会提出别的东西:

你要创建一个“CarFactory”将返回一个具体的实现你的基类/接口。 Create方法可以将测试条件作为参数,以便创建正确的汽车。

编辑:这里有一个从MSDN的链接 - http://msdn.microsoft.com/en-us/library/ms954600.aspx

编辑:见另一条链路的意见。

相关问题