虚拟方法重载解析 [英] Overload resolution of virtual methods

查看:95
本文介绍了虚拟方法重载解析的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑代码



<预类=郎-CS prettyprint-覆盖> 公共类基地
{
公虚拟INT添加(int类型的,INT b)
{
返回A + b;
}
}

公共类派生:基本
{
公共覆盖INT添加(INT A,INT B)
{
返回A + b;
}

公众诠释添加(浮动,浮动B)
{
回报率(的Int32)(A + B);
}
}

如果我创建派生类的一个实例,并调用添加用它为什么调用带有浮动参数的Add方法



<预类=郎-CS prettyprint-覆盖> 派生的obj =新的int类型的参数派生()
obj.Add(3,5)

//这是为什么调用
添加(浮动,浮动b)

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


解决方案

这是由设计。 C#语言规范规定的第7.5.3节:




例如,设置一个方法调用考生不包括标重写方法(§7.4),如果在派生类的任何方法都是适用的(§7.6.5.1)在一个基类的方法不是候选




在换句话说,因为你的派生类有一个非重写添加法,添加方法在基本类(在派生)是不再候选人重载。



虽然 Base.Add(INT,INT)将是一个更好的匹配, Derived.Add(浮动,浮动)是否存在等指基类的方法,甚至从未被编译器认为。



埃里克利珀讨论了一些原因,这个设计中的这个博客帖子


Consider the code

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);
   }
}

If I create an instance of Derived class and call Add with parameters of type int why it is calling the Add method with float parameters

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

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

Why it is not calling the more specific method?

解决方案

This is by design. Section 7.5.3 of the C# language specification states:

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).

In other words, because your Derived class has a non-overridden Add method, the Add method in the Base class (and its overridden version in Derived) are no longer candidates for overload resolution.

Even though Base.Add(int,int) would be a better match, the existance of Derived.Add(float,float) means that the base class method is never even considered by the compiler.

Eric Lippert discusses some of the reasons for this design in this blog post.

这篇关于虚拟方法重载解析的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆