【发布时间】:2018-02-12 14:13:26
【问题描述】:
我在编码方面还是个新手,所以我想知道这是否/如何工作?
//a class with armor with subclasses to say what part of the body it go's
public class Armor
{
//stuff that applies to all armor
}
public class HeadArmor : Armor
{
//stuff for HeadPieces only
}
public class ChestArmor : Armor
{
}
//etc
//the class that stores what armor is equiped
public class MainCharacterEquipment
{
//the class of my maincharacter
public MainCharacter HeroEquipment { get; set; }
public HeadArmor HeadSlot { get; set; }
public ChestArmor ChestSlot { get; set; }
//etc
//a constructor that sets all to null
public void EquipArmor(Armor armor)
{
if (armor is HeadArmor)
{
HeadSlot = armor; //compile error
}
if (armor is ChestArmor)
{
ChestSlot = armor; //compile error -> Missing a cast?
}
//etc
}
}
如果我这样做,它会询问我是否缺少演员表。 从这个论坛上的阅读看来,子类是主类的一种 但反之则不然。
为了解决这个问题,我可以为每个盔甲子类创建一个方法。 我不会使用(Armor Armor)作为参数,而是使用(HeadArmor headArmor),(ChestArmor chestArmor)等...... 但这似乎很乏味。 我还读到 typeof() 和 is 之间有区别,但我也不太明白。 最好我只是将对象装甲投射到它的子类中。当然,if 函数应该检查它是否已经是子类(如果有意义的话)
ps:实际上没有 Armor 对象的实例。只有子类的对象被实例化。 (有没有关系)
【问题讨论】:
-
try
if ( armor is HeadArmor hArmor ) { HeadSlot = hArmor; } ...如果类型匹配,这也会进行强制转换。当然,还有更多解决方案……但从简单开始。 -
@Korosevar 你是在为 Unity 开发这些东西吗?如果是这样,模式匹配将不起作用
-
@Fildor 我得到错误:hArmor 在当前上下文中不存在
-
为什么不把 HeadSlot 和 ChestSlot 都做成 Armor 类型呢?这就是多态性大放异彩的时候。
-
那是哪个平台? .Net 框架 4.7 ? .Net 核心?统一? ...这可能会排除一些解决方案...
标签: c# class casting type-conversion