如何绕过任何派生类的提问并编写代码两次?
我尝试了以下内容:
Type t = GetType(obj);
(obj as t).health
通过这样做,Visual Sudio说明health is not member of... blah
这是我的代码:
// gameobjects-class
abstract gameobject
{
Vector2 Position
void update()
etc...
class meteor : gameobject
{
float rotation
etc...
class player : gameobject
{
int health, attackpower
etc...
class enemy: gameobject
{
int health, attackpower
etc...
从GameObject
class anyclass
{
void checkhealth(gameobject obj) // QUESTION:
{
if (obj as player).health = 0 //
kill(obj) //
if (obj as enemy).health = 0 //
kill(obj) //
有什么建议吗?谢谢!
答案 0 :(得分:0)
您可以为活动对象创建一个接口,然后将其传递给方法
interface ILivingGameObject
{
int Health {get;set;}
}
class Player : GameObject, ILivingGameObject
{
}
void CheckHealth(ILivingGameObject obj)
{
if(obj.Health == 0)
kill(obj);
}
您可以在界面here
上阅读更多内容或者你可以创建一个LivingObject
类,玩家和敌人都继承这个类并将其传递给方法
class LivingObject : GameObject
{
int Health {get;set;}
}
class Player : LivingObject
{
}
void CheckHealth(LivingObject obj)
{
}