c# - 继承:根据具体对象在运行时调用正确的方法

标签 c# inheritance

我有以下类(class):

public class Person
{
}

public class Employee : Person
{
}

public class Customer : Person
{
}

使用这些类的一些方法:

public class OtherClass
{
    public void DoSomething(Employee e)
    {
    }

    public void DoSomething(Customer c)
    {
    }
}

通话:

// People = Collection<Person>.
foreach (var p in People)
    DoSomething(p); // Should call the right method at runtime and "see" if it´s an Employee or a Customer.

编译器不允许这样做。我如何实现这个场景?

最佳答案

这里最简单的方法是多态性,即

public class Person
{
    public virtual void DoSomething() {} // perhaps abstract?
}

public class Employee : Person
{
    public override void DoSomething() {...}
}

public class Customer : Person
{
    public override void DoSomething() {...}
}

并使用:

foreach (var p in People)
    p.DoSomething();

但是!如果不可能,那就作弊:

foreach (var p in People)
    DoSomething((dynamic)p); // TADA!

另一种选择是自己检查类型:

public void DoSomething(Person p)
{
    Employee e = p as Employee;
    if(e != null) DoSomething(e);
    else {
        Customer c = p as Customer;
        if(c != null) DoSomething(c);
    }
}

关于c# - 继承:根据具体对象在运行时调用正确的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12742465/

相关文章:

java - 如何从子类的子类获取在父类(super class)中实例化的对象的字段

c# - SqlParameter 和 IN 语句

c# - Visual Studio C# 2010 速成版中的对象浏览器在哪里?

c# - 自定义用户控件 - 如何添加类型为 Dictionary<int, Color> 的代码集合编辑器

c# - 在方法中传递对派生对象的引用时出错

java - List<Dog> 是 List<Animal> 的子类吗?为什么 Java 泛型不是隐式多态的?

C++ 继承可见性模式

c# - PayPal 支付标准从移动设备返回 GET 而不是 POST,因此无法验证记录支付

c# - 比较两个列表

c++ - 在基类没有虚方法的派生类中声明虚方法是否错误?