加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-15 06:28:11 所属栏目:百科 来源:网络整理
导读:考虑代码 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); }} 如果我创建一个Deriv
考虑代码
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讨论了这一设计的一些原因.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读