class BaseClass
{
public virtual void M(int x)
{
}
}
class Derived : BaseClass
{
public override void M(int x)
{
base.M(x);
}
static void M(object x)
{
}
static void Main()
{
var d = new Derived();
d.M(0);
}
}
错误:
A member lookup of a name N with K type parameters in a type T is processed as follows:
[...] Members that include an override modifier are excluded from the set [of accessible members named N]
由此我得出这样的结论:
Member 'Derived.M(object)' cannot be accessed with an instance reference; qualify it with a type name instead
在C#4.0规范7.4节(会员查询)第一点读展望覆盖Derived.M
不再可访问。相反,编译器必须参考BaseClass.M
。
但是,这并不能解释为什么添加静态Derived.M
突然导致编译错误。编译器现在只能看到静态成员Derived.M
,并得出结论说这个成员是无效的调用。如果我删除静态Derived.M
,则编译成功。
为什么会发生这种情况?
http://www.akadia.com/services/dotnet_polymorphism.html – MethodMan 2013-02-21 16:08:16
这似乎将对象作为静态方法的参数存在问题。如果我将该参数更改为字符串,它可以正常工作。 – cadrell0 2013-02-21 16:09:00
有趣的是,像Eric Lippert这样的人可能会被迫(或者真的)试图编写可以解决这样问题的编译器,这里的真正教训是不会为编译器创建棘手的问题当不同的名字同样有效时,避免给大量的标识符同名。 – Servy 2013-02-21 16:13:23