[英]Can not cast from source type to destination type
我正在Unity中编写游戏,并且尝试使用多态来访问2个子类,但始终出现错误:
无法从源类型转换为目标类型
我有一个Places
的序列化列表,并且我试图向下转换到Property
,它是Place
的子类。 我如何在Unity中做到这一点?
((Property)Board.GetBoardPlace(Players[PlayerTurn].Position)).Owner = Players[PlayerTurn];
如果您使用基本类型Place
最初实例化了Place
类型列表中的项目,那么我认为您不能/应该以这种方式下调(或者更确切地说,进行类型转换) ,至少不能使用C#这样的托管语言。 。 在填充列表时,请考虑重新设计或实例化为Property
类型的项目:
List<Place> Places = new List<Place>();
Places.Add(new Property());
然后,以后可以在需要使用它们时将它们强制转换为Property
类型:
Property property = Places[0] as Property;
if (property != null){
// Conversion successful
}
在这个Stack Overflow问题中,您可以阅读更多内容。 希望这可以帮助! 如果您有任何疑问,请告诉我。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.