为什么要编译此C#类声明? [英] Why does this C# class declaration compile?

查看:145
本文介绍了为什么要编译此C#类声明?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个问题确实没有意义,但是我很好奇:

This question really is kinda pointless, but I'm just curious:

此:

public sealed class MyClass
{
   protected void MyMethod(){}
}

编译,但发出警告

在此期间:

public sealed class MyClass
{
   public virtual void MyMethod(){}
}

不会编译.只是出于好奇,这是有原因的吗?

doesn't compile. Just out of sheer curiosity, is there a reason for this?

推荐答案

我能想到的唯一原因是,有时您需要编写受保护的方法来覆盖其他受保护的方法.语言可以被设计为允许这种情况:

The only reason I can think of is that sometimes you would need to write protected methods to override other protected methods. The language could have been designed to allow this:

protected override void Foo()

但不是这个

protected void Foo()

但是可能很难理解-只是override 使得它无用,而对于

but that might have been seen to be a little hard to follow - it's the absence of override which makes it useless, whereas in the case of

public virtual void Foo()

状态没用.与没有有用的东西相比,存在错误"的东西可能更容易理解.

it's the presence of virtual that is useless. The presence of something "wrong" is probably easier to understand than the absence of something useful.

在这种情况下,虚拟化也可能会对性能产生影响,而使受保护的东西而不是私有的东西可能没有效果-因此情况会更加严峻.

In this case, being virtual may also have performance implications, whereas making something protected instead of private probably doesn't - so it's a bit more severe.

这些实际上只是猜测-如果我们真的很幸运,埃里克·利珀特(Eric Lippert)将给出更明确的答案.他是你想要的人,不是我:)

These are just guesses though really - if we're really lucky, Eric Lippert will give a more definitive answer. He's the one you want, not me :)

最佳答案:将警告视为错误,无论如何它们都是等效的;)

Best answer: treat warnings as errors and they're equivalent anyway ;)

这篇关于为什么要编译此C#类声明?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆