【问题标题】:C# overload and override method [duplicate]C#重载和覆盖方法[重复]
【发布时间】:2018-03-27 10:44:57
【问题描述】:

我有一个扩展另一个类的类,我想像在构造函数中那样覆盖和重载一个方法。

类似这样的东西(这只是为了说明我想要什么):

public class A {
    someMethod(int i){
        //Do something
    }
}

public class B : A {
     someMethod(int i, int j) : base(i){
         //Do something more
     }
}

我怎样才能重现这样的东西?

【问题讨论】:

  • someMethod 是公开的吗?受保护?
  • 首先为您的函数指定访问修饰符...
  • 并应用.NET naming conventions,没有小写的方法名称,所以pascal-不是骆驼大小写。
  • 那不是真正的代码,只是我正在尝试做的一个说明;)

标签: c# overriding overloading


【解决方案1】:

您可以从子类中调用继承的方法,这种方法称为重载(添加一个名称相同但参数不同的方法):

public class A 
{
    // note that the method must not be private 
    // in order to be able to call it from intherited classes
    protected void someMethod(int i){
        //Do something
    }
}

public class B : A {
     // however, this class may be private of it needs to be
     void someMethod(int i, int j) 
     {
         this.someMethod(i); 
         // Do something more
     }
}

您也可以写base.someMethod(i); 或根本不写任何说明符,因为它是多余的,但就个人而言,我发现this 比省略说明符更明确。在这种特定情况下,这并不重要。

然而,如果您使用this(或省略说明符)覆盖继承类中的方法将调用被覆盖的方法,而使用base 将调用基类的实现,所以您可能需要注意该细节。


只是为了指出不同之处。 重载就像“换出”或更具体地,修改或扩展继承类中的实现,同时保留方法的原始签名(名称和参数):

public class A 
{
    // again, note that the method must not be private 
    // in order to be able to call it from intherited classes
    protected virtual void someMethod(int i){
        //Do something
    }
}

public class B : A {
     protected override void someMethod(int i) 
     {
         this.someMethod(i); 
         // Do something more
     }
}

【讨论】:

  • protected void someMethod(int i){..} 默认方法是private
  • this.someMethod(i); 关键字this冗余
  • 它不起作用:B.someMethod(int, int) 被标记为覆盖,但找不到合适的方法来覆盖
  • 你说它更方便,但this.someMethodbase.someMethod 可能是非常不同的东西。
  • 你还在说this很方便,这真是个糟糕的建议。
猜你喜欢
  • 1970-01-01
  • 2021-12-02
  • 1970-01-01
  • 2013-01-15
  • 1970-01-01
  • 2020-04-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多