静态类声明受保护成员

发布于 2024-11-18 08:10:27 字数 451 浏览 4 评论 0原文

我正在阅读“C# Language”这本书,并点击了此注释弗拉基米尔·列舍特尼科夫:

如果静态类声明了受保护的或 受保护的内部成员,发生编译时错误 (CS1057 )。

我可以知道为什么吗? 具有受保护成员的静态类有什么问题? 静态类可以有私有成员,所以我猜这个 CS1057 错误不是由于可访问性引起的,但可能是由于编译问题引起的?因为受保护的成员可以在子类中被覆盖......但我不明白为什么。

I'm reading the book "C# Language", and hit this note from Vladimir Reshetnikov:

If a static class declares a protected or
protected internal member, a compile-time error occurs (CS1057).

May I know why?
What's wrong with a static class having a protected member?
Static class can have private member so I guess this CS1057 error is not due to accessibility, but maybe it's due to come compilation issue? as protected member could be overridden in child classes... but I couldn't figure out why.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(3

雄赳赳气昂昂 2024-11-25 08:10:27

因为您无法继承静态类,所以 protected 没有任何作用 - 只有 publicprivate 在这里才有意义。

更多详细信息可以在这里找到:为什么我不能继承静态类?

Because you can't inherit a static class, protected serves no purpose - only public and private make sense here.

More details can be found here: Why can't I inherit static classes?

多孤肩上扛 2024-11-25 08:10:27

受保护的成员意味着可以从子类/派生类访问它们。但静态类的主要特点是:

  1. 仅包含静态成员;

  2. 无法实例化;

  3. 已密封。

这就是静态类不能有受保护成员的原因。

Protected members means they can be accessed from child/derived classes. But the main features of static class are:

  1. Only contain static members;

  2. Can't be instantiated;

  3. Are sealed.

That's why static classes can't have protected members.

冷情 2024-11-25 08:10:27

.NET 中的继承仅适用于实例基础。静态方法是在类型级别而不是实例级别定义的。这就是为什么重写不适用于静态方法/属性/事件...

静态方法仅在内存中保存一次。没有为它们创建虚拟表等。

如果您在 .NET 中调用实例方法,则始终为其提供当前实例。这被 .NET 运行时隐藏,但它确实发生了。每个实例方法都有一个指向运行该方法的对象的指针(引用)作为第一个参数。静态方法不会发生这种情况(因为它们是在类型级别定义的)。编译器应该如何决定选择要调用的方法?

(小大师)

Inheritance in .NET works only on instance base. Static methods are defined on the type level not on the instance level. That is why overriding doesn't work with static methods/properties/events...

Static methods are only held once in memory. There is no virtual table etc. that is created for them.

If you invoke an instance method in .NET, you always give it the current instance. This is hidden by the .NET runtime, but it happens. Each instance method has as first argument a pointer (reference) to the object that the method is run on. This doesn't happen with static methods (as they are defined on type level). How should the compiler decide to select the method to invoke?

(littleguru)

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