C# 抽象方法:内部公共和虚拟?
C# 中的抽象方法在内部是公共的还是虚拟的?
默认情况下,所有方法都是私有的,如果抽象方法是私有的,则派生类将无法使用它,从而产生错误“虚拟或抽象成员不能是私有的”
Are abstract methods internally public and virtual in c#?
All methods are, by default, private and if an abstract method is private, it will not be available to derived class, yielding the error "virtual or abstract members cannot be private"
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我认为你问的问题与大多数人想象的不同(换句话说,你似乎理解
abstract
的含义)。您不能声明私有抽象方法 - 编译器会发出错误。这两个类都不会编译:
编译器阻止您声明无用的方法,因为私有抽象成员不能在派生类中使用,并且对声明类没有实现(因此没有用处)。
需要注意的是,编译器应用于抽象成员的默认访问修饰符(如果您自己没有指定)仍然是
private
,就像方法不是抽象的情况一样。I think you are asking a different question than most people think (in other words it seems like you understand what
abstract
means).You cannot declare a private abstract method - the compiler issues an error. Both of these classes will not compile:
The compiler is preventing you from declaring a useless method since a private abstract member cannot be used in a derived class and has no implementation (and therefore no use) to the declaring class.
It is important to note that the default access modifier applied to an abstract member by the compiler (if you do not specify one yourself) is still
private
just like it would be if the method was not abstract.摘要只是一种表达方式:“我在这里,但还没人告诉我要做什么。”由于没有人实施该成员,所以必须有人这样做。为此,您必须继承该类并覆盖该成员。
为了能够覆盖某些内容,必须将其声明为
abstract
或virtual
,并且必须至少可供继承者访问,即必须标记为protected、<代码>内部或<代码>公共。
Abstract is just a way to say: "I am here, but no one has told me what I'm going to do yet." And since no one has implemented that member yet someone must do that. To do that you have to inherit that class, and override that member.
To be able to override something it has to be declared either
abstract
orvirtual
, and must at least be accessible to the inheritor, i.e. must be markedprotected
,internal
orpublic
.抽象方法不能是私有的并且是虚拟的。他们至少必须受到保护。
Abstract methods cannot be private and are virtual. They must be at least protected.
凭借 Jon Skeet 的论点(默认访问权限是什么C# 中的修饰符?)它必须是“受保护的”正如 Pieter 所指出的,默认值始终是私有的,因此:
给出编译器错误
By virtue of Jon Skeet's argument here (What are the Default Access Modifiers in C#?)It must be "protected"As pointed out by Pieter default is always private, so:
Gives compiler error