[英]inheritence C# using new functions
我正在用C#制作游戏。 我创建了基类Shape
和其他七个从Shape
继承的类( Shape1
, Shape2
等)。 在我的主程序中,我使用以下命令跟踪当前正在播放的形状
Shape Current;
然后,我将其值随机化为等于以下形状之一,例如:
Current = new Shape1()
问题是,在我随机化之后,我想用
Current.Draw()
每个形状都有自己的Draw
函数,我希望它专门使用该函数,而不是Shape
的函数。 我怎样才能做到这一点?
您所描述的概念称为多态性 (将不同的对象类型作为一种对象进行处理)。
在C#中,您可以通过virtual
, abstract
和override
关键字进行此操作。 在基类中,将多态方法标记为virtual
或abstract
,区别在于abstract
方法必须由派生类定义:
public abstract void Draw();
请注意, virtual
方法必须定义主体,而abstract
方法则不能 。 然后,在派生类中,使用override
关键字定义相同的方法:
public override void Draw()
{
//whatever implementation
}
有关更多信息,请参见MSDN。
我必须说@BradleyDotNet很好地解释了这一点,我只是添加了一个实际的示例,可能有助于阐明它的用法。 注意我如何使用所有虚拟,抽象和覆盖关键字。
using System;
namespace ShapeExample
{
class Program
{
public static void Main(string[] args)
{
for (int i = 0; i < 20; i++)
{
var shape = GetRandomShape();
shape.Draw();
}
}
public static Random Random = new Random();
public static Shape GetRandomShape()
{
var d = Random.Next(3);
switch (d)
{
case 1:
return new Shape1();
case 2:
return new Shape2();
default:
return new Shape3();
}
}
}
public abstract class Shape
{
public virtual void Draw()
{
//Console.WriteLine("General Shape");
Console.WriteLine(" _");
Console.WriteLine(" / \\ ");
Console.WriteLine("/___\\");
}
}
public class Shape1 : Shape
{
public override void Draw()
{
//Console.WriteLine("I want a square instead");
Console.WriteLine(" ____");
Console.WriteLine("| |");
Console.WriteLine("|____|");
}
}
public class Shape2 : Shape
{
public override void Draw()
{
//Console.WriteLine("I want a complicated circle instead");
double r = 3.0;
double r_in = r - 0.4;
double r_out = r + 0.4;
for (double y = r; y >= -r; --y)
{
for (double x = -r; x < r_out; x += 0.5)
{
double value = x * x + y * y;
if (value >= r_in * r_in && value <= r_out * r_out)
{
Console.Write('*');
}
else
{
Console.Write(' ');
}
}
Console.WriteLine();
}
}
}
public class Shape3 : Shape
{
//I don't care how I look like, I'm using the regular shape drawing.
//but I have some particular info that is not part of a regular Shape
public int ParticularField { get; }
public Shape3()
{
ParticularField = -100;
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.