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

c# – 重载分辨率奇怪

发布时间:2020-12-15 04:19:21 所属栏目:百科 来源:网络整理
导读:不确定这是否是特定的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); }}
不确定这是否是特定的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.

(编辑:李大同)

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

    推荐文章
      热点阅读