为什么 C# 编译器重载解析算法将具有相同签名的静态成员和实例成员视为相等?

发布于 2024-11-07 23:46:03 字数 592 浏览 7 评论 0原文

让我们有两个签名相等的成员,但一个是静态的,另一个不是:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

一身仙ぐ女味 2024-11-14 23:46:03

那么,从实例方法来看:

Test();

那会调用什么?您可能希望赋予实例方法相对于静态方法的“优先级”,但两者都适用。

我想说,即使允许,从可读性的角度来看,这样做从根本上来说也是一个坏主意……例如,如果您将名为 Test 的方法从静态更改为例如,它会以微妙的方式改变含义。

换句话说,我对禁止这样做没有任何问题:)

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.

In other words, I have no problem with this being prohibited :)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文