[英]Why does C# compiler overload resolution algorithm treat static and instance members with equal signature as equal?
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 类型'Foo'已经定义了一个名为'Test'的成员,它具有相同的参数类型
But why? 但为什么?
Let we compiled that successfully, then: 让我们成功编译,然后:
Foo.Test()
should output "static" Foo.Test()
应输出“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: 无法调用静态成员而不是实例1,因为在这种情况下会出现另一个更合理的编译器错误:
Member 'Foo.Test()' cannot be accessed with an instance reference; 无法使用实例引用访问成员'Foo.Test()'; qualify it with a type name instead 用类型名称来限定它
What about, from an instance method: 从实例方法怎么样:
Test();
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. 我会说,即使它被允许,从可读性的角度来看这是一个根本不好的想法...例如,如果你改变了一个名为Test
的方法,从静态到实例,它会改变意思是微妙的。
In other words, I have no problem with this being prohibited :) 换句话说,我对此被禁止没有问题:)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.