在该方法的重写中调用基本抽象方法
Call a base abstract method in an override of that method
我发现 here 这个 link 与我的问题相似,但我似乎还是不明白。
public abstract class ClassA
{
protected abstract void Method()
{
//some logic here
}
}
public class ClassB : ClassA
{
protected override void Method()
{
base.Method();
// some custom logic here
}
}
这是我的情况,我似乎无法找出为什么我无法从 ClassB 中的重写方法调用 base.Method()
。错误显示:"cannot call an abstract base method"。如果我不能调用它,为什么还要有逻辑填充和抽象基方法的功能?有人可以向我解释一下我犯了什么错误吗?我该如何改正?
来自 C# 规范:
An abstract method is a virtual method with no implementation. An
abstract method is declared with the abstract modifier and is
permitted only in a class that is also declared abstract. An abstract
method must be overridden in every non-abstract derived class.
所以无法实现抽象方法。因此抽象方法不能有主体:
protected abstract void Method();
如果您想在基础 class 中使用一些默认逻辑,您必须声明方法 virtual
:
protected virtual void Method()
{
//some logic here
}
关键字abstract
意味着派生classes必须实现该方法,但抽象class本身不提供任何实现(因此错误)。
我认为您可能正在寻找 virtual
,它既提供了一些基本功能,又允许实现 classes 来覆盖行为。
来自MSDN Website:
It is a compile-time error for a base-access (Section 7.5.8) to
reference an abstract method. In the example
abstract class A
{
public abstract void F();
}
class B: A
{
public override void F()
{
base.F(); // Error, base.F is abstract
}
}
a compile-time error is reported for the base.F()
invocation because
it references an abstract method.
我发现 here 这个 link 与我的问题相似,但我似乎还是不明白。
public abstract class ClassA
{
protected abstract void Method()
{
//some logic here
}
}
public class ClassB : ClassA
{
protected override void Method()
{
base.Method();
// some custom logic here
}
}
这是我的情况,我似乎无法找出为什么我无法从 ClassB 中的重写方法调用 base.Method()
。错误显示:"cannot call an abstract base method"。如果我不能调用它,为什么还要有逻辑填充和抽象基方法的功能?有人可以向我解释一下我犯了什么错误吗?我该如何改正?
来自 C# 规范:
An abstract method is a virtual method with no implementation. An abstract method is declared with the abstract modifier and is permitted only in a class that is also declared abstract. An abstract method must be overridden in every non-abstract derived class.
所以无法实现抽象方法。因此抽象方法不能有主体:
protected abstract void Method();
如果您想在基础 class 中使用一些默认逻辑,您必须声明方法 virtual
:
protected virtual void Method()
{
//some logic here
}
关键字abstract
意味着派生classes必须实现该方法,但抽象class本身不提供任何实现(因此错误)。
我认为您可能正在寻找 virtual
,它既提供了一些基本功能,又允许实现 classes 来覆盖行为。
来自MSDN Website:
It is a compile-time error for a base-access (Section 7.5.8) to reference an abstract method. In the example
abstract class A
{
public abstract void F();
}
class B: A
{
public override void F()
{
base.F(); // Error, base.F is abstract
}
}
a compile-time error is reported for the
base.F()
invocation because it references an abstract method.