不确定这是否是特定的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(对象,对象).
解决方法
我认为对于解析方法调用它首先在它的类中查找,因为DayOfWeek可以作为对象类型传递,它调用类自己的方法,而不是基类中的方法.
在第二种情况下,方法调用解析为更具体的类型参数,因此调用Foo(对象栏,DayOfWeek日).
来自MSDN – Method resolution.
methods in a base class are not candidates if any method in a derived@H_403_37@ 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@H_403_37@ argument list,provided that each function member is compared to all@H_403_37@ 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.