【问题标题】:How to override a function without redefine in c#?如何在不重新定义 C# 的情况下覆盖函数?
【发布时间】:2013-04-18 22:20:47
【问题描述】:

我有一个要求,我有一个类和一个函数

   public  class BaseClass
        {
            public virtual int MyMethod(int n)
            {
                Console.WriteLine("BaseClass=" + n + "+" + 2);
                return n + 2;
            }
        }

和一个派生类 b 我在哪里扩展基类函数

 public class A : BaseClass
        {
            public override int MyMethod(int n)
            {
                Console.WriteLine("Class A=" + n+"*"+2);
                return n*2;
            }
        }

在我调用函数 A.MyMethod() 时在派生类中 基函数应该在派生类函数之后执行。

static void Main(string[] args)
        {

            A classA = new A();
            A.MyMethod(1);

            Console.ReadKey();
        }

有可能吗?

【问题讨论】:

  • 你需要更清楚你的要求。您的原始代码无法编译也无济于事。
  • 请看更新后的代码。
  • 那仍然无法编译 - 你想改为调用 classA.MyMethod。如果你想先调用基类方法,那么只需让A.MyMethod 这样做——用base.MyMethod(n) 开始实现。

标签: c# oop


【解决方案1】:

你的意思是你想从派生构造函数调用基构造函数?是的,您可以使用 base() 构造来做到这一点。

public Derived(int sides)
    : base(sides)

当 Square() 实际上不是构造函数(它在你的问题中,没有返回类型或 void)而是一个方法时,你可以这样做:

public override returntype Foo(...)
{
    // your adaptation
    base.Foo(...)

基类中的方法必须是虚拟的才能工作。

【讨论】:

    【解决方案2】:
    class b: a
    {   
        public new int Square(int n)
        {
          var baseResult = base.Square(n);
          var i = 0//extenting the code
          return i;
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-05-15
      • 2012-11-10
      • 2013-01-30
      • 2012-02-08
      • 1970-01-01
      • 2016-06-01
      • 1970-01-01
      • 2018-08-14
      相关资源
      最近更新 更多