Dav*_*wer 39 c# abstract-class pure-virtual
我被告知要让我的课抽象:
public abstract class Airplane_Abstract
并制作一个名为move virtual的方法
 public virtual void Move()
        {
            //use the property to ensure that there is a valid position object
            double radians = PlanePosition.Direction * (Math.PI / 180.0);
            // change the x location by the x vector of the speed
            PlanePosition.X_Coordinate += (int)(PlanePosition.Speed * Math.Cos(radians));
            // change the y location by the y vector of the speed
            PlanePosition.Y_Coordinate += (int)(PlanePosition.Speed * Math.Sin(radians));
        }
而另外4种方法应该是"纯虚拟方法".究竟是什么?
它们现在看起来都像这样:
public virtual void TurnRight()
{
    // turn right relative to the airplane
    if (PlanePosition.Direction >= 0 && PlanePosition.Direction < Position.MAX_COMPASS_DIRECTION)
        PlanePosition.Direction += 1;
    else
        PlanePosition.Direction = Position.MIN_COMPASS_DIRECTION;  //due north
}
Jon*_*eet 75
我的猜测是,任何告诉你编写"纯虚拟"方法的人都是C++程序员而不是C#程序员...但等效的是抽象方法:
public abstract void TurnRight();
这迫使具体的子类覆盖TurnRight真实的实现.
它们可能意味着应该标记方法abstract.
 public abstract void TurnRight();
然后,您需要在子类中实现它们,而不是空虚拟方法,其中子类不必覆盖它.
小智 6
纯虚函数是 C++ 的术语,但在 C# 中,如果在派生类中实现的函数和派生类不是抽象类。
abstract class PureVirtual
{
    public abstract void PureVirtualMethod();
}
class Derivered : PureVirtual
{
    public override void PureVirtualMethod()
    {
        Console.WriteLine("I'm pure virtual function");
    }
}
或者甚至你可以去界面,认为需要一些小限制:
public interface IControllable
{
    void Move(int step);
    void Backward(int step);
}
public interface ITurnable
{
   void TurnLeft(float angle);
   void TurnRight(float angle);
}
public class Airplane : IControllable, ITurnable
{
   void Move(int step)
   {
       // TODO: Implement code here...
   }
   void Backward(int step)
   {
       // TODO: Implement code here...
   }
   void TurnLeft(float angle)
   {
       // TODO: Implement code here...
   }
   void TurnRight(float angle)
   {
       // TODO: Implement code here...
   }
}
但是,您必须实现两者的所有函数声明IControllable并ITurnable已赋值,否则将发生编译器错误。如果您想要可选abstract class的虚拟实现,则必须使用虚拟方法和interface纯虚拟方法。
其实interfacefunction和abstractfunction是有区别的,interface只声明了function,所有的interfacefunction都必须是public的,所以没有诸如privateor之类的花哨的类属性,protected所以速度非常快,而abstractfunction是实际的类方法,没有实现,强制实现在派生类中,所以你可以把private,protected和访问成员变量与abstract功能,以及大部分的时间是慢,因为类的继承关系在运行时分析。(又名 vtable)