简体   繁体   English

来自抽象派生类的过程函数和变量

[英]process functions and variables from derived class of abstract

How do i circumvent questioning from any derived class and writing the code twice? 我如何规避来自任何派生类的询问并编写两次代码?

I have tried the following: 我尝试了以下方法:

Type t = GetType(obj); 
(obj as t).health

By doing this, Visual Sudio saysme health is not member of... blah 通过这样做,Visual Sudio说我的health is not member of... blah

Here's my code: 这是我的代码:

// 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...

External class accessing data from GameObject 外部类从GameObject访问数据

class anyclass
{
void checkhealth(gameobject obj)   // QUESTION:
{
if (obj as player).health = 0      // 
     kill(obj)                     // 
if (obj as enemy).health = 0       // 
     kill(obj)                     // 

Any suggestion? 有什么建议吗? Thanks! 谢谢!

You can create an interface for living objects and then pass that to the method 您可以为活动对象创建接口,然后将其传递给方法

interface ILivingGameObject
{
    int Health {get;set;}
}

class Player : GameObject, ILivingGameObject
{
}

void CheckHealth(ILivingGameObject obj)
{
     if(obj.Health == 0)
          kill(obj);
}

You can read more on Interfaces here 您可以在此处阅读有关接口的更多信息


Alternatively you can create a LivingObject class that both player and enemy inherit from and pass this to the method 或者,您可以创建一个既包含玩家又包含敌人的LivingObject类,并将其传递给方法

class LivingObject : GameObject
{
    int Health {get;set;}
}

class Player : LivingObject
{
}

void CheckHealth(LivingObject obj)
{
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM