C# 中“抽象覆盖"的用途是什么? [英] What is the use of 'abstract override' in C#?
问题描述
出于好奇,我尝试覆盖基类中的抽象方法,并对实现抽象进行方法.如下:
公共抽象类 FirstAbstract{公共抽象无效 SomeMethod();}公共抽象类 SecondAbstract : FirstAbstract{公共抽象覆盖 void SomeMethod();//??这有什么意义?无论如何都没有实现会强制派生类实现抽象方法?}
想知道为什么 C# 编译器允许编写抽象覆盖".不是多余的吗?做这样的事情应该是一个编译时错误.它是否适用于某些用例?
感谢您的关注.
Microsoft Docs - 基本上您可以强制派生类为方法提供新的实现.
公共类D{public virtual void DoWork(int i){//原始实现.}}公共抽象类 E : D{公共抽象覆盖 void DoWork(int i);}公开课 F : E{公共覆盖无效 DoWork(int i){//新的实现.}}
<块引用>
如果一个虚方法被声明为抽象的,它对任何人来说仍然是虚的从抽象类继承的类.一个类继承了一个抽象方法不能访问原始实现方法——在前面的例子中,F类上的DoWork不能调用DoWork在 D 类上.这样抽象类就可以强制派生类为虚方法提供新的方法实现.
Just out of curiosity I tried overriding a abstract method in base class, and method the implementation abstract. As below:
public abstract class FirstAbstract
{
public abstract void SomeMethod();
}
public abstract class SecondAbstract : FirstAbstract
{
public abstract override void SomeMethod();
//?? what sense does this make? no implementaion would anyway force the derived classes to implement abstract method?
}
Curious to know why C# compiler allows writing 'abstract override'. Isn't it redundant? Should be a compile time error to do something like this. Does it serve to some use-case?
Thanks for your interest.
There's a useful example for this on Microsoft Docs - basically you can force a derived class to provide a new implementation for a method.
public class D
{
public virtual void DoWork(int i)
{
// Original implementation.
}
}
public abstract class E : D
{
public abstract override void DoWork(int i);
}
public class F : E
{
public override void DoWork(int i)
{
// New implementation.
}
}
If a virtual method is declared abstract, it is still virtual to any class inheriting from the abstract class. A class inheriting an abstract method cannot access the original implementation of the method—in the previous example, DoWork on class F cannot call DoWork on class D. In this way, an abstract class can force derived classes to provide new method implementations for virtual methods.
这篇关于C# 中“抽象覆盖"的用途是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!