[英]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.