为什么 C# 编译器重载解析算法将具有相同签名的静态成员和实例成员视为相等?
让我们有两个签名相等的成员,但一个是静态的,另一个不是:
class Foo
{
public void Test() { Console.WriteLine("instance"); }
public static void Test() { Console.WriteLine("static"); }
}
但这样的代码生成会带来编译器错误:
类型“Foo”已经定义了一个名为“Test”的具有相同参数类型的成员
但是为什么呢?
让我们编译成功,然后:
Foo.Test()
应该输出“static”- < p>
new Foo().Test();
应该输出“instance”
可以' t 调用静态成员而不是实例一,因为在这种情况下另一个更合理会出现编译错误:
无法通过实例引用访问成员“Foo.Test()”;使用类型名称来限定它
Let we have two members equal by signature, but one is static and another - is not:
class Foo
{
public void Test() { Console.WriteLine("instance"); }
public static void Test() { Console.WriteLine("static"); }
}
but such code generate brings a compiler error:
Type 'Foo' already defines a member called 'Test' with the same parameter types
But why?
Let we compiled that successfully, then:
Foo.Test()
should output "static"new Foo().Test();
should output "instance"
Can't call the static member instead of instance one because in this case another, more reasonable compiler error will occur:
Member 'Foo.Test()' cannot be accessed with an instance reference; qualify it with a type name instead
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
那么,从实例方法来看:
那会调用什么?您可能希望赋予实例方法相对于静态方法的“优先级”,但两者都适用。
我想说,即使允许,从可读性的角度来看,这样做从根本上来说也是一个坏主意……例如,如果您将名为
Test
的方法从静态更改为例如,它会以微妙的方式改变含义。换句话说,我对禁止这样做没有任何问题:)
What about, from an instance method:
What would that call? You'd probably want to give the instance method "priority" over the static method, but both would be applicable.
I would say that even if it were allowed, it would be a fundamentally bad idea to do this from a readability point of view... for example, if you changed a method which called
Test
from being static to instance, it would change the meaning in a subtle way.In other words, I have no problem with this being prohibited :)