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

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.

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

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

相关推荐