C# - 继承、覆盖

标签 c# inheritance types

我可以做这样的事情吗? (过于简单,因为它太复杂了)

abstract class A {
  public string Print() {}

  public static string DoPrint(A a, Type T) {
    ((T)a).Print(); // <-- This should call eg. A3.Print(), not A.Print()
  }
}

class A1: A {
  public new string Print() {}
}

class A2: A {

}

class A3: A {
  public new string Print() {}
}

class Somewhere
{
  A3 a3 = new A3();
  a3.DoPrint();
}

我有许多继承自基类 (A) 的类(A1、A2、A3 等)

我正在尝试在 A 类中创建上面的 DoPrint() 函数。 可以吗?

我试过了

  public static string DoPrint(A a) {
    a.Print();
  }

但它调用的是 A.Print(),而不是 A3.Print()

编辑:将标题从“将类型作为参数传递?”更改为因为大家都是对的,我可以只使用虚拟(谢谢!)。问题出在别处,与这个问题无关。

最佳答案

public static string DoPrint(A a) {
  a.Print();
}

可以工作,但您需要将 Print 声明为虚拟并覆盖它。

    abstract class A {
      public virtual string Print() {}

      public static string DoPrint(A a) {
          a.Print();
      }
    }

    class A1: A {
      public override string Print() {}
    }

    class A2: A {
      public override string Print() {}
    }

    class A3: A {
      public override string Print() {}
    }

    class Somewhere
    {
      A3 a3 = new A3();
      A.DoPrint(a3);
    }

关于C# - 继承、覆盖,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7525395/

相关文章:

c# - 从 C# 中的列表框值填充组合框

c# - 委托(delegate)不接受子类?

sql - 将 varchar 值 'Blue color' 转换为数据类型 int 时转换失败

powershell - 为什么 `[SomeType] | Get-Member -Static`返回 `SomeType`的静态成员而不是 `System.RuntimeType`的静态成员?

C#:在 xml 标记中搜索值

c# - 如何在 Web 应用程序中获取用户的互联网连接速度?

c# - 可以得到 "operator"结果的引用吗?

c# - 如何在C#中继承WPF控件并同时使用泛型类?

oop - 如何将组合与继承结合使用?

c# - 找不到类型或命名空间名称 'Bussen'(您是否缺少 using 指令或程序集引用?)