[英]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.我首先想使用泛型构造函数创建 2 个新类,而不是使用它们的函数。 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.一个类应该将第二个类作为参数来使用方法 Attack() 和动态 (class2.health - class1.damage),但它必须实现一个 IDamagable 接口。
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);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.