C#中的纯虚方法?

时间:2011-02-09 18:35:24

标签: 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
}

7 个答案:

答案 0 :(得分:72)

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

public abstract void TurnRight();

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

答案 1 :(得分:11)

“Pure virtual”是C ++术语。 C#等价物是一种抽象方法。

答案 2 :(得分:8)

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

 public abstract void TurnRight();

然后,您需要在子类中实现它们,而不是空虚拟方法,其中子类不必覆盖它。

答案 3 :(得分:4)

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

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函数和abstract函数之间存在差异, interface仅声明函数,所有interface函数都有为了公开所以没有像privateprotected这样的花哨类属性,所以它非常快,而abstract函数是实际的类方法没有实现强制实现派生类,因此您可以放置​​privateprotected并使用abstract函数访问成员变量,以及大多数时候它的速度较慢,因为在运行时分析了类继承关系。 (又名vtable)

答案 4 :(得分:4)

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

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

class Derivered : PureVirtual
{
    public override void PureVirtualMethod()
    {
        Console.WriteLine("I'm pure virtual function");
    }
}

答案 5 :(得分:2)

然后你没有在Airplane_Abstract Class中实现,但是迫使消费者和#34;继承者&#34;实现它们的类。

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

答案 6 :(得分:1)

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

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

Google始终是您的朋友。

相关问题