什么是C#中使用“抽象覆盖”的? [英] What is the use of 'abstract override' in C#?
问题描述
只是出于好奇,我试图重写在基类中的抽象方法,和方法的实施抽象。如下图所示:
公共抽象类FirstAbstract
{
公共抽象无效的someMethod();
}公共抽象类SecondAbstract:FirstAbstract
{
公共抽象覆盖无效的someMethod();
//?这确实让什么意义?没有implementaion无论如何都会迫使派生类实现抽象的方法?
}
想知道为什么C#编译器允许写抽象覆盖。是不是多余的?应该是一个编译时错误做这样的事情。它是否满足某些用例?
感谢您的关注。
有一个有用的例子,这个上的 MSDN - 基本上你可以强制派生类中提供的方法的新的实施
D公共类
{
公共虚拟无效的DoWork(int i)以
{
//原始的实现。
}
}公共抽象E类:D
{
公共抽象覆盖无效的DoWork(int i)以;
}公共F类:电子
{
公共覆盖无效的DoWork(int i)以
{
//新的实现。
}
}
如果一个虚拟方法声明抽象的,它仍然是虚拟的任何
类从抽象类继承。 类的继承
抽象方法不能访问原始实施
方法 - 在previous例如,DoWork的对F级不能打电话的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 MSDN - 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屋!