微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

c# – 虚拟方法的重载分辨率

考虑代码
public class Base
{
   public virtual int Add(int a,int b)
   {
      return a+b;
   }
}

public class Derived:Base
{
   public override int Add(int a,int b)
   {
      return a+b;
   }

   public int Add(float a,float b)
   {
      return (Int32)(a + b);
   }
}

如果我创建一个Derived类的实例,并调用Add类型的参数,为什么它调用带有float参数的Add方法

Derived obj =new Derived()
obj.Add(3,5)

// why this is calling 
Add(float a,float b)

为什么不调用更具体的方法

解决方法

这是设计. C#语言规范第7.5.3节规定:

For example,the set of candidates for a method invocation does not include methods marked override (§7.4),and methods in a base class are not candidates if any method in a derived class is applicable (§7.6.5.1).

换句话说,因为您的Derived类具有非重载的Add方法,所以Base类中的Add方法(以及Derived中的被覆盖的版本)不再适用于重载解析.

即使Base.Add(int,int)将是一个更好的匹配,Derived.Add(float,float)的存在意味着基类方法从来没有被编译器考虑.

Eric Lippert在this blog post讨论了这一设计的一些原因.

原文地址:https://www.jb51.cc/csharp/95488.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐