c# - 将具有相同接口(interface)或基类的类传递给重载方法

标签 c#

我有一个具有 x 个属性的基类,然后我有一个具有更多属性的派生类。如何处理方法中的公共(public)字段,然后将对象发送到另一个可以处理其附加属性的方法?

例子:

public Interface IAnimal {
    int NoOfFeet;
}

class Animal: IAnimal {
    int NoOfFeet {get;set;}
}

class Elephant: Animal {
   bool hasTrunk {get;set;}
}

class Dog:Animal {
   string canBark {get;set;}
}

Method1(IAnimal a) {
    //process NoOfFeet     ...

    //process fields for derived type
    DoSomething(IAnimal a)
}    

DoSomething(Elephant e) {
     //process trunk
}

DoSomething(Dog d) {
     //process canbark
}

最佳答案

听起来您基本上希望在执行时解决重载问题。 (我假设你不能引入一个虚拟方法来做正确的事情,并在每个类中实现它。如果实现知道你在用它们做什么是合理的,那将是最干净的方法,但那是并非总是如此。)最简单的实现方式是使用 dynamic,如 C# 4 中所介绍的:

public void Method(IAnimal animal)
{
    // We don't want to call Handle with a null reference,
    // or we'd get an exception to due overload ambiguity
    if (animal == null)
    {
        throw new ArgumentNullException("animal");
    }
    // Do things with just the IAnimal properties
    Handle((dynamic) animal);
}

private void Handle(Dog dog)
{
    ...
}

private void Handle(Elephant elephant)
{
    ...
}

private void Handle(object fallback)
{
    // This method will be called if none of the other overloads
    // is applicable, e.g. if a "new" implementation is provided
}

关于c# - 将具有相同接口(interface)或基类的类传递给重载方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30897144/

相关文章:

c# - 一种实时获取自上次调用方法以来经过的毫秒数的方法

c# - 使用linq计算gridview中的特定特征

c# - Windows phone sdk 使用 XNA 游戏引擎发送电子邮件

c# - 不允许使用 WHERE 子句的 SqlDependency 查询。我怎样才能修改它是有效的?

javascript - 在 react 18 中使用 makeStyles Material UI 没有结果

c# - 如何使用绑定(bind)嵌套 View ?

c# - 只要没有单击任何项​​目,就阻止 ToolStripDropDownButton 关闭

c# - 返回包含 MediatR 管道行为错误的响应

c# - 如何在泛型类型的构造函数中分配泛型类型的成员?

c# - 将 'set' 添加到 C# 中的接口(interface)属性