C#继承/多态

标签 c# inheritance polymorphism

假设有以下类:

public class Animal
{
}

public class Dog : Animal
{
     public void Bark()
     {
     }
}

public class Cat : Animal
{
     public void Meow()
     {
     }
}


Animal cat = Cat();
Animal dog = Dog();
PatternIamLookingFor.DoSomething(cat); // -> Call Meow
PatternIamLookingFor.DoSomething(dog); // -> Call Bark

这可能吗?没有向 Animal 基类添加 MakeNoise() 之类的方法?

在我的应用程序中,我有一个 CatFactory 和一个 DogFactory,它们实现 AnimalFactory 并返回 Animals。厂里不能叫Meow/bark,拿到动物后也不能叫。

最佳答案

我可以想出几种方法来实现上述内容。

1。使用接口(interface)

如果您可以修改原始源代码,这可能是最好的选择。易于实现,易于维护。

public interface IDoSomething
{
    void DoSomething();
}

public class Dog : Animal, IDoSomething
{
     public void Bark()
     {
     }

     void IDoSomething.DoSomething(){
         Bark();
     }
}

public class Cat : Animal, IDoSomething
{
     public void Meow()
     {
     }

     void IDoSomething.DoSomething(){
         Meow();
     }
}

2。使用 Adapters

如果您无法访问原始源代码,适配器可能是唯一的选择。您可以使用它们来“同步”代码访问 Cat 和 Dog 类的方式。您仍然可以像使用原始对象一样使用适配器,但使用更适合新代码需求的修改接口(interface)。创建一个工厂以根据父类型创建适当的适配器会相当简单。

public IDoSomething
{
    void DoSomething()
    {
    }
}

public DoSomethingFactory
{

    public static IDoSomething( Animal parent )
    {
        if ( typeof( parent ) is Dog )
            return new DoSomethingDog( parent as Dog );
        if ( typeof( parent ) is Cat )
            return new DoSomethingCat( parent as Cat );
        return null;
    }

}

public DoSomethingDog : Dog, IDoSomething
{
    Dog _parent;
    public DoSomethingDog( Dog parent )
    {
        _parent = parent;
    }

    public void DoSomething()
    {
        _parent.Bark();
    }
}

public DoSomethingCat : Cat, IDoSomething
{
    Cat _parent;
    public DoSomethingCat( Cat parent )
    {
        _parent = parent;
    }

    public void DoSomething()
    {
        _parent.Meow();
    }
}

除了这两个明显的实现之外,您可能还需要考虑以下这些:

  • 使用 Decorators动态增强类的功能。 (类似于上面的“包装器”方法,但更干净地融入类结构中。)

  • 实现一系列 Command您的类可以动态处理的对象:

    cat.Do( new MakeNoiseCommand() ); // Handled as "meow"
    dog.Do( new MakeNoiseCommand() ); // Handled as "bark"
    
  • 允许类似于 Mediator 的内容根据 Animal 的类型等转发请求:

    public class AnimalMediator
    {
        public void MakeNoise( Animal animal )
        {
            if ( typeof( animal ) is Dog ) (animal as Dog).Bark();
            else if ( typeof( animal ) is Cat ) (animal as Cat).Meow();
        }
    }
    

关于C#继承/多态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19102724/

相关文章:

c# - 在我的应用程序中如何关闭 Winword.exe

iOS 如何在不子类化所有内容的情况下为类引入具有 UDID 的能力?

java - Java 中除了多态性还有其他选择吗?

c++ - 具有通用方法和数据结构的策略

java - 方法重载 int 与 Short

c# - : UITableView and keyboard scrolling issue 的 Xamarin 解决方案

c# - 我如何将代码更改为linq样式

c# - WPF - 两个不同 ViewModel 上的绑定(bind)和命令

java - 输入并不会一直传递给 children

c# - 我可以从实例化的类继承吗?