Skip to main content
 首页 » 编程设计

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

2024年02月20日15tintown

我有以下类(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); 
    } 
}