简体   繁体   English

如果虚拟方法被声明为abstract

[英]If a virtual method is declared abstract

My friend asks me if an abstract method could have virtual modifier. 我的朋友问我抽象方法是否可以有虚拟修饰符。 And I said, No . 我说, Because, an abstract method is implicitly also a virtual method, it cannot have the modifier virtual. 因为抽象方法也隐式也是虚方法,所以它不能具有虚拟修饰符。

But while reading one of the MSDN articles , I have seen this: 但在阅读MSDN文章之一时 ,我看到了这一点:

... If a virtual method is declared abstract , it is still virtual to any class inheriting from the abstract class. ...如果虚拟方法被声明为abstract ,则它仍然是从抽象类继承的任何类的虚拟方法。 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.... 继承抽象方法的类无法访问方法的原始实现 - 在前面的示例中,类F上的DoWork无法在类D上调用DoWork。这样,抽象类可以强制派生类为虚方法提供新方法实现....

I can't understand first sentence correctly. 我无法正确理解第一句话。 Could you please, explain me what they wants to say? 你能不能解释一下他们想说什么?

Thanks. 谢谢。

It becomes clearer when you look at the code example directly above the quoted paragraph: 当您查看引用段落正上方的代码示例时,它会变得更清晰:

public class D
{
    public virtual void DoWork(int i)
    {
        // Original implementation.
    }
}

public abstract class E : D
{
    public abstract override void DoWork(int i);
}

The virtual method D.DoWork is inherited by E , and, there, declared abstract. 虚拟方法D.DoWorkE继承,并且在那里声明为abstract。 The method is still virtual , it has just become abstract as well . 该方法仍然虚拟的 ,它也刚刚变得抽象

As you correctly state, an abstract method is always virtual. 正确地说,抽象方法总是虚拟的。 If your friend is still unconvinced, here's an official quote for that: 如果你的朋友仍然不相信,这里有一个官方报价

An abstract method is implicitly a virtual method. 抽象方法隐含地是虚方法。

Abstract classes may override virtual members with abstract ones: 抽象类可以使用abstract类覆盖virtual成员:

public class B
{
    public virtual void M() { }
}
public abstract class D : B
{
    public abstract override void M();
}
public abstract class D2 : D
{
    public override void M() { }
}

The sentence says that D2 must override void M() , because it is declared abstract in D . 句子说D2 必须覆盖void M() ,因为它在D被声明为abstract。 If it were declared as D2 : B , this would be optional, but as it stands, D2 has to comply with the contracts specified in D , but M() will also behave like any other member overriding a "normal" virtual member, since M() is both virtual and abstract. 如果它被声明为D2 : B ,这将是可选的,但是就目前而言, D2必须遵守D指定的合同,但M()也将像任何其他成员一样覆盖“正常”虚拟成员,因为M()既是虚拟的也是抽象的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM