Skip to main content
 首页 » 编程设计

C# 继承多态类型

2024年02月06日12me-sa

从一个名为 Weapon 的基本类开始,我希望它是多态的,如下所示:

public class Weapon 
{ 
    // Some code.. 
} 
 
public class MachineGun : Weapon 
{ 
    // Extend the base code.. 
} 

这些类定义了基本功能,但是它们不包含绘制武器的任何代码。这个画图只需要在Client应用中添加,Server端直接使用MachineGun类即可,不需要可视化。

public class DrawableWeapon : Weapon 
{ 
    // Adding draw calls and properties 
} 
 
public class DrawableMachineGun : DrawableWeapon 
{ 
    // The problem: 
    // You have no access to the properties of the original MachineGun here 
} 
// or.. 
public class DrawableMachineGun : MachineGun 
{ 
    // Same problem, only now you miss properties of the DrawableWeapon 
} 

问题是丢失了 MachineGun() 类或 DrawableWeapon() 类的功能,因为 C# 没有多重继承。

将 Weapon 类定义为接口(interface)也没有成功,您不能在接口(interface)中定义方法,这正是我需要减少代码的地方。

我找到的唯一(部分)解决方案是方法:在单独的静态类中定义它们,并且在可绘制类中的每个方法调用中,也调用此静态方法。这仍然遗漏了所有属性,并导致长时间的方法调用。

最好的选择是什么?在这种情况下是否可以使用更好的编程模式?

请您参考如下方法:

是的。您可以使用 Decorator图案:

    public class Weapon 
    { 
       public virtual void Shot() 
       {  
          // Some code... 
       } 
    } 
 
    public class MachineGun : Weapon 
    { 
       public override void Shot() 
       {  
          // Extend base code... 
       } 
    } 
 
    public class DrawableWeapon : Weapon 
    { 
       Weapon mWeapon; 
 
       public override void Shot() 
       {  
          mWeapon.Shot(); 
       } 
 
        // Adding draw calls and properties 
    }