继承和服务类 [英] Inheritance and service class

查看:94
本文介绍了继承和服务类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我认为OOP中最基本的东西:

It's, I think somethin basic in OOP :

环境:C#/.net 2.0

Environment : C#/.net 2.0

假设我有两个班级:

public class Animal
{

}
public class Dog : Animal
{

}

具有两种方法的服务类:

A service class with two method :

 public void DoStuff(Animal animal)
    {
        Console.Write("Animal stuff");
    }
    public void DoStuff(Dog animal)
    {
        Console.Write("Dog stuff");
    }

如果我执行以下代码:

 Animal instance = new Animal();
        MyService.DoStuff(instance);

        Animal instance2 = new Dog();
        MyService.DoStuff(instance2);

动物性物品"打印两次.

"Animal stuff" is printed twice.

所以我的问题是:为什么?以及如何在不强制转换instance2或将方法从服务移至类的情况下获得动物材料"和狗材料"(实际上,我希望我的代码可以工作,但不是:()

So my question is : why ? And how can I get "Animal stuff" and "Dog stuff" without casting instance2, or moving the method from my service to my class (in fact I would like that my code works, but it's not :()

谢谢

PS:这些只是示例:)

PS : These are just example :)

由于访问者"模式并不是很吸引人,因此我将把服务的方法移到类中,等待更好的解决方案.

Because the Visitor pattern is not really appealing, I'll just move my service's method to my class, waiting for a better solution.

推荐答案

由于参数类型不同,因此您不会覆盖Dog中的doStuff()方法.它们是两种不同的方法.

You aren't overriding the doStuff() method in Dog, because the parameter type is different. They're two separate methods.

要么更改狗"中的签名以匹配动物",要么创建访客"以为您对其进行分类.

Either change the signature in Dog to match Animal or create a Visitor that sorts it out for you.

这是一种编写方式:

public interface Animal {  void accept(AnimalVisitor visitor); }

public class AbstractAnimal : Animal
{
    public void accept(AnimalVisitor visitor) { visitor.visit(this); } 
}

public class Dog : AbstractAnimal {}

public class Cat : AbstractAnimal {}

public interface AnimalVisitor
{
    void visit(Animal animal);
    void visit(Dog dog);
    void visit(Cat cat);
}

现在,该服务(以及所有其他服务)可以实现AnimalVisitor并对每个Animal子类型执行不同的操作.

Now the service (and all others) can implement AnimalVisitor and do different things to each Animal subtype.

这是一种常见的模式,称为双重调度";您可以在Scott Meyers的更有效的C ++"中详细了解它.

It's a common pattern called "double dispatch"; you can read more about it in Scott Meyers' "More Effective C++".

这篇关于继承和服务类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆