C# 如何定义必须继承的类
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11172964/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to define a must inherit class
提问by thechmodmaster
How to define a must inherit class? in C#
如何定义必须继承的类?在 C# 中
采纳答案by Oded
You mark the class as abstract(this is the C# analogue to the VB.NET Must Inherit).
您将类标记为abstract(这是与 VB.NET 类似的 C# Must Inherit)。
This will ensure it can't be instantiated directly.
这将确保它不能被直接实例化。
From the linked MSDN article:
来自链接的 MSDN 文章:
The abstract modifier indicates that the thing being modified has a missing or incomplete implementation. The abstract modifier can be used with classes, methods, properties, indexers, and events. Use the abstract modifier in a class declaration to indicate that a class is intended only to be a base class of other classes. Members marked as abstract, or included in an abstract class, must be implemented by classes that derive from the abstract class.
抽象修饰符表示被修改的事物缺少或不完整的实现。abstract 修饰符可用于类、方法、属性、索引器和事件。在类声明中使用抽象修饰符来指示一个类仅用作其他类的基类。标记为抽象或包含在抽象类中的成员必须由从抽象类派生的类实现。
(emphasis mine)
(强调我的)
回答by zmbq
You can define a class as abstract, or give it a protected-only constructor. abstractis better.
您可以将一个类定义为abstract,或者给它一个仅受保护的构造函数。abstract更好。
回答by Jeremy Wiggins
Use the abstractmodifier.
使用abstract修饰符。
public abstract class MyClass()
{
...
}
回答by Tigran
It's not possible enforse needness of derivation or implementation in code, if thatwas a question.
如果这是一个问题,则不可能在代码中强制要求派生或实现。
But:
但:
You can define an interfaceto force consumer to implementit.
您可以定义一个interface以强制消费者实现它。
Or you can define abstract classwith only abstract members to force consumer to override allof them.
或者您可以abstract class仅使用抽象成员进行定义以强制消费者覆盖所有成员。
Hope this helps.
希望这可以帮助。
回答by Nihar Dodiya
If u want to create a class, that has to be inherited, you'll need to mark it with the abstractmodifier.
如果你想创建一个必须被继承的类,你需要用abstract修饰符标记它。
public abstract MyClass
{
}

