抽象方法和虚拟方法有什么区别?在哪些情况下,建议使用抽象方法或虚拟方法?哪一种是最好的方法?


当前回答

我在一些地方看到抽象方法的定义如下**

“必须在子类中实现抽象方法”

**我觉得是这样。

如果子类也是抽象的,则不必在子类中实现抽象方法。。

1) 抽象方法不能是私有方法。2) 抽象方法不能在同一抽象类中实现。

我会说。。如果我们要实现一个抽象类,您必须重写基础抽象类中的抽象方法。因为使用重写关键字实现抽象方法。类似于虚拟方法。

虚拟方法不必在继承类中实现。

                                 ----------CODE--------------

public abstract class BaseClass
{
    public int MyProperty { get; set; }
    protected abstract void MyAbstractMethod();

    public virtual void MyVirtualMethod()
    {
        var x = 3 + 4;
    }

}
public abstract class myClassA : BaseClass
{
    public int MyProperty { get; set; }
    //not necessary to implement an abstract method if the child class is also abstract.

    protected override void MyAbstractMethod()
    {
        throw new NotImplementedException();
    }
}
public class myClassB : BaseClass
{
    public int MyProperty { get; set; }
    //You must have to implement the abstract method since this class is not an abstract class.

    protected override void MyAbstractMethod()
    {
        throw new NotImplementedException();
    }
}

其他回答

当您希望继承者根据需要扩展功能时,基本上可以使用虚拟方法。

当您希望继承者实现功能时,可以使用抽象方法(在这种情况下,他们别无选择)

答案已经提供了很多次,但关于何时使用每一个的问题是设计时的决定。我认为,尝试将通用方法定义捆绑到不同的接口中,并将它们拉到适当抽象级别的类中是一种很好的做法。当最好定义一个实现一组简洁接口的非抽象类时,将一组通用的抽象和虚拟方法定义转储到一个类中会使该类不可实例化。一如既往,这取决于什么最适合您的应用程序特定需求。

必须始终重写抽象函数。

因此:

抽象函数-当继承者必须提供自己的实现时虚拟-由继承人决定

抽象函数不能具有功能。你基本上是说,任何子类都必须给出自己版本的这个方法,但是它太通用了,甚至无法在父类中实现。

一个虚拟函数,基本上就是说,看,这里的功能对于子类来说可能不够好,也可能不够好。因此,如果它足够好,请使用此方法,如果不好,请重写我,并提供您自己的功能。

我在一些地方看到抽象方法的定义如下**

“必须在子类中实现抽象方法”

**我觉得是这样。

如果子类也是抽象的,则不必在子类中实现抽象方法。。

1) 抽象方法不能是私有方法。2) 抽象方法不能在同一抽象类中实现。

我会说。。如果我们要实现一个抽象类,您必须重写基础抽象类中的抽象方法。因为使用重写关键字实现抽象方法。类似于虚拟方法。

虚拟方法不必在继承类中实现。

                                 ----------CODE--------------

public abstract class BaseClass
{
    public int MyProperty { get; set; }
    protected abstract void MyAbstractMethod();

    public virtual void MyVirtualMethod()
    {
        var x = 3 + 4;
    }

}
public abstract class myClassA : BaseClass
{
    public int MyProperty { get; set; }
    //not necessary to implement an abstract method if the child class is also abstract.

    protected override void MyAbstractMethod()
    {
        throw new NotImplementedException();
    }
}
public class myClassB : BaseClass
{
    public int MyProperty { get; set; }
    //You must have to implement the abstract method since this class is not an abstract class.

    protected override void MyAbstractMethod()
    {
        throw new NotImplementedException();
    }
}