C# 使用一种变量类型引用我的一系列类中的任何一个?
对于C#来说,这是一个非常新的问题,对你们大多数人来说,这可能是一个简单的问题。我只是对这方面没有什么经验 假设我有一个为太空船创建和处理模型、控件、声音等的类,因此:C# 使用一种变量类型引用我的一系列类中的任何一个?,c#,class,variables,C#,Class,Variables,对于C#来说,这是一个非常新的问题,对你们大多数人来说,这可能是一个简单的问题。我只是对这方面没有什么经验 假设我有一个为太空船创建和处理模型、控件、声音等的类,因此: Ship myShip = new Ship(); 创建了飞船,我可以看到它,那里一切都很好,我可以用“飞船”访问它的变量,我可以制作另一个并称之为其他东西。。但是如果我有另一门课,那是一个。。战舰。。再说一个战士。。战斗中舰船的AI有一个“目标”。所以我可以用: Ship target; “目标”将引用当前目标,它可能会更
Ship myShip = new Ship();
创建了飞船,我可以看到它,那里一切都很好,我可以用“飞船”访问它的变量,我可以制作另一个并称之为其他东西。。但是如果我有另一门课,那是一个。。战舰。。再说一个战士。。战斗中舰船的AI有一个“目标”。所以我可以用:
Ship target;
“目标”将引用当前目标,它可能会更改为另一个舰船实例,但我的问题是,是否有一个变量类型可以处理这些类别中的任何一个,比如说目标从舰船实例切换到战列舰。我会得到一个错误,它不能从战舰类型转换为战舰
如果没有这样的变量类型,是否有更简单的方法来实现这一点,而不是为可能成为目标的每种类型的类使用不同的变量
以防万一我不太清楚。。我基本上希望这项工作不会出错:
WhatsThisHere target = new Ship();
target = new DifferentTypeOfShip();
谢谢 您可以创建
public class Ship {
//Common behaviour and parameters for every ship in the world
}
public class BattleShip : Ship {
// get basic Ship behavior and adds it's
// own battle specific properties and functions
}
因此,在代码中,您确实喜欢:
Ship me = new BattleShip();
Ship enimy = new BattleShip();
me.Target = enimy;
让所有看起来像船的类型从
ship
派生:
public class BattleShip : Ship
{
}
您可以做的一件事是创建一个接口,您的所有船只都可以从该接口实现。通过这种方式,您可以创建公共函数/方法(请注意,接口无法在函数中实现任何代码,因为接口是抽象的),并在类中实现这些函数/方法。比如说
public interface IShipInterface
{
//any common properties here
//any common methods/functions here
void Target();
void AnythingElseYouNeed();
}
public class Ship : IShipInterface
{
//fields
public Ship()
{
//constructor
}
public void Target()
{
//implement your ship Target method here
throw new NotImplementedException();
}
public void AnythingElseYouNeed()
{
//implement other function code here
throw new NotImplementedException();
}
}
public class BattleShip : IShipInterface
{
//fields
public BattleShip()
{
//constructor
}
public void Target()
{
//here is your battleship targetting, which could be completely different from your ship targetting.
throw new NotImplementedException();
}
public void AnythingElseYouNeed()
{
throw new NotImplementedException();
}
}
从这里你可以像这样创造它们
IShipInterface ship = new Ship();
IShipInterface battleShip = new BattleShip();
这具有优势,因为您的所有船只都可以通过ShipInterface类型引用,例如在foreach循环中
foreach (IShipInterface ship in ShipList.OfType<BattleShip>())
{
//all your battleships
}
foreach(ShipList.OfType()中的IShipInterface ship)
{
//你所有的战舰
}
使用一个接口并从中继承Ship
。那么你的目标就不需要只是飞船了
interface ITargetable
{
//
}
class Ship : ITargetable
{
//
}
在另一个类中,您将只使用
ITargetable
非常感谢您的帮助(以及其他所有人:D)循环也将非常有用..没问题:)如果您需要更多帮助,请随时询问!