47

我被告知要让我的班级抽象:

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
}
4

7 回答 7

93

我的猜测是,告诉您编写“纯虚拟”方法的人是 C++ 程序员而不是 C# 程序员……但等效的是抽象方法:

public abstract void TurnRight();

这迫使具体的子类被TurnRight真实的实现覆盖。

于 2011-02-09T18:36:43.767 回答
12

“纯虚拟”是 C++ 术语。C# 等价物是一种抽象方法。

于 2011-02-09T18:36:53.400 回答
11

他们可能意味着方法应该被标记abstract

 public abstract void TurnRight();

然后,您将需要在子类中实现它们,而不是一个空的虚拟方法,子类不必重写它。

于 2011-02-09T18:36:31.593 回答
6

纯虚函数是 C++ 的术语,但在 C# 中,如果在派生类中实现的函数且该派生类不是抽象类。

abstract class PureVirtual
{
    public abstract void PureVirtualMethod();
}

class Derivered : PureVirtual
{
    public override void PureVirtualMethod()
    {
        Console.WriteLine("I'm pure virtual function");
    }
}
于 2016-01-22T08:29:00.733 回答
5

甚至你可以去界面,认为需要一些小限制:

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...
   }
}

但是,您必须实现两者的所有函数声明IControllableITurnable已赋值,否则会发生编译器错误。如果您想要可选的虚拟实现,则必须abstract class使用interface纯虚拟方法和虚拟方法。

interface实际上, function 和abstractfunction是有区别的,interface只声明 function,所有interface函数都必须公开,所以没有花哨的类属性,比如privateorprotected所以它非常快,而abstractfunction 是没有实现的实际类方法强制实现在派生类中,所以你可以用函数来放置privateprotected访问成员变量abstract,而且大多数时候速度较慢,因为在运行时分析了类继承关系。(又名 vtable)

于 2015-03-16T05:50:46.887 回答
2

然后,您在 Airplane_Abstract 类中没有实现,而是强制该类的消费者“继承者”实现它们。

在继承和实现抽象函数之前,Airplane_Abstract 类是不可用的。

于 2011-02-09T18:38:18.743 回答
-1

http://en.wikipedia.org/wiki/Virtual_function

“在面向对象的编程中,虚函数或虚方法是一种函数或方法,其行为可以在继承类中被具有相同签名的函数覆盖。”

谷歌永远是你的朋友。

于 2011-02-09T18:38:09.933 回答