[英]Can abstract class be used as non base class?
I am new to C# programming. 我是C#编程的新手。 I understand that it is necessary to modify the class as abstract if it contains any abstract methods, and its implementation must be provided in any of the child classes in class hierarchy. 我了解,如果类包含任何抽象方法,则有必要将其修改为抽象类,并且必须在类层次结构中的任何子类中提供其实现。
But my question is whether can we have an abstract class without any abstract methods(so it is not necessary for it to be a base class) , and if it is so, then what are the significance of the same. 但是我的问题是我们是否可以有一个没有任何抽象方法的抽象类(因此它不必成为基类) ,如果是这样,那么它的意义何在? Please help in this regard. 请帮助这方面。 :) :)
Yes you can have an abstract
base class without any abstract methods. 是的,您可以有一个没有任何抽象方法的abstract
基类。 The benefit is that you cannot create an instance of this class. 好处是您无法创建此类的实例。
There is a consideration to replace that abstract class with an interface. 考虑使用接口替换该抽象类。 The difference is that the interface may not contain any implementation, but in the abstract class you can provide some implementation for methods that any inheritor may use. 区别在于该接口可能不包含任何实现,但是在抽象类中,您可以为任何继承者可以使用的方法提供一些实现。
您无法创建抽象类的实例,并且如果您不使用此类作为基础-它是无用的(仅对于使用反射的一些棘手目标而言可能)
Yes, it can be used without having an implementing subclass. 是的,可以在没有实现子类的情况下使用它。 Basically you have three "ways" of defining and calling methods here: 基本上,这里有三种“方式”来定义和调用方法:
The following simple console app gives a nice, concrete (no pun intended) example: 以下简单的控制台应用程序给出了一个很好的,具体的(无双关语)示例:
using System;
namespace ConsoleStuff
{
public abstract class MyAbstractClass
{
public abstract void DoSomethingAbs();
public void DoSomethingElse()
{
Console.WriteLine("Do something general...");
}
public static void TakeABreak()
{
Console.WriteLine("Take a break");
}
}
class MyImplementation : MyAbstractClass
{
public override void DoSomethingAbs()
{
Console.WriteLine("Do something Specific...");
}
}
class Program
{
static void Main(string[] args)
{
// Static method; no instance required
MyAbstractClass.TakeABreak();
var inst = new MyImplementation();
inst.DoSomethingAbs(); // Required implementation in subclass
inst.DoSomethingElse(); // Use method from the Abstract directly
Console.ReadKey();
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.