简体   繁体   中英

How could I pass generic interface as a method parameter?

So I'm currently experimenting with generics and I've just stumbled upon a mind shaking problem. I really have an abstract idea of how that could work, but after searching for answers I got more confused.

I first want to create 2 new classes using generic constructors, than use their functions. One class should take in a second class as a parameter to use method Attack() and dynamically(class2.health - class1.damage), but it has to implement an IDamagable interface.

I may do weird mistakes. Sorry.

public class GenericsIdeas : MonoBehaviour
{

public interface IDamagable<T>
{
    void TakeDamage(T dmg);
}

public class Enemy<T1, T2> : IDamagable<T1>
{
    T1 damage;
    T2 health;

    public void Attack(IDamagable d)
    {
        d.TakeDamage((dynamic)damage);
    }

    public void TakeDamage(T1 damage)
    {
        dynamic dmg = (dynamic)damage;
        dynamic hp = (dynamic)health;
        health -= dmg;
        Debug.Log("Enemy health: " + health);
    }

    public Enemy(T1 t1, T2 t2)
    {
        damage = t1;
        health = t2;
    }
}

public class Player<T1, T2> : IDamagable<T1>
{
    T1 damage;
    T2 health;

    public void Attack(IDamagable d)
    {
        d.TakeDamage((dynamic)damage);
    }

    public void TakeDamage(T1 damage)
    {
        dynamic dmg = (dynamic)damage;
        dynamic hp = (dynamic)health;
         health -= dmg;
        Debug.Log("Player health: " + health);
    }

    public Player(T1 t1, T2 t2)
    {
        damage = t1;
        health = t2;
    }
}

void Start()
{
    Player<int, int> player = new Player<int, int>(6, 10);
    Enemy<float, float> enemy = new Enemy<float, float>(4.32f, 20.61f);
    player.Attack(enemy.IDamagable); //???
}
}

I would suggest this transformation:

public interface IDamagable
{
    void TakeDamage<T>(T dmg);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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