c# – 重载分辨率奇怪

不确定这是否是特定的C#4,但只是注意到了这一点.

考虑以下类:

class Base
{
  protected void Foo(object bar,DayOfWeek day)
  {
  }
}

class Program : Base
{
  protected void Foo(object bar,object baz)
  {
  }

  void Bar(DayOfWeek day)
  {
    Foo(new { day },day);
  }
}

在Bar中调用Foo,解析为Foo(对象,对象).

将其更改为:

class Base
{

}

class Program : Base
{
  protected void Foo(object bar,object baz)
  {
  }

  protected void Foo(object bar,DayOfWeek day)
  {
  }

  void Bar(DayOfWeek day)
  {
    Foo(new { day },解析为Foo(object,DayOfWeek).

我的理解是它应该像第二个例子一样解决.

这是一个错误’还是我缺乏理解(或无知)?

更新:

谢谢你的回答.正如我所知,可以使用base.在基类中调用方法.然而,当在混合中添加一个派生类时,问题又回来了.

class Base
{
  protected void Foo(object bar,object baz)
  {
  }

  void Bar(DayOfWeek day)
  {
    base.Foo(new { day },day);
  }
}

class Derived : Program
{
  void Baz(DayOfWeek day)
  {
    base.Foo(new { day },day);
  }
}

基地.调用在Program中工作,但随后解析为Derived中的Foo(对象,对象).

如何在Derived中调用Foo(object,DayOfWeek)而不必在Program中创建“冗余”方法

解决方法

我认为对于解析方法调用它首先在它的类中查找,因为DayOfWeek可以作为对象类型传递,它调用类自己的方法,而不是基类中的方法.

在第二种情况下,方法调用解析为更具体的类型参数,因此调用Foo(对象栏,DayOfWeek日).

来自MSDN – Method resolution.

methods in a base class are not candidates if any method in a derived
class is applicable
(Section 07001).

  • Given the set of applicable candidate function members,the best function member in that set is located.
  • If the set contains only one function member,then that function member is the best function member.
  • Otherwise,the best function member is the one function member that is better than all other function members with respect to the given
    argument list
    ,provided that each function member is compared to all
    other function members using the rules in Section 7.4.2.2.
  • If there is not exactly one function member that is better than all other function members,then the function member invocation is ambiguous and a compile-time error occurs.

相关文章

在要实现单例模式的类当中添加如下代码:实例化的时候:frmC...
1、如果制作圆角窗体,窗体先继承DOTNETBAR的:public parti...
根据网上资料,自己很粗略的实现了一个winform搜索提示,但是...
近期在做DSOFramer这个控件,打算自己弄一个自定义控件来封装...
今天玩了一把WMI,查询了一下电脑的硬件信息,感觉很多代码都...
最近在研究WinWordControl这个控件,因为上级要求在系统里,...