2016-08-24 48 views
1

我需要知道如何将方法传递给类构造函数,以便稍后调用它。这个想法是有一个Bullet类,它有两个属性,一个损害整数和一个Method,当这个类型的子弹击中一个对象时可以调用它。下面的代码应该解释好一点:如何将方法保存在稍后要执行的类中

public class Bullet 
{ 
    public Method OnHit; 
    public int Damage; 
    public Bullet(int Damage,Method OnHit) 
    { 
     this.Damage = Damage; 
     this.OnHit = OnHit; 
    } 
} 

这让我可以作出这样通过运行这样Bullet.OnHit(HitGameObject)瓶坯在撞击不同的任务子弹。

回答

3

您可以使用Action将函数传递给函数,然后将其存储在另一个Action中。存储的功能可以使用Action.Invoke()调用。

public class Bullet 
{ 
    public int Damage; 
    System.Action savedFunc; 

    public Bullet(int Damage, System.Action OnHit) 
    { 
     if (OnHit == null) 
     { 
      throw new ArgumentNullException("OnHit"); 
     } 

     this.Damage = Damage; 
     savedFunc = OnHit; 
    } 

    //Somewhere in your Bullet script when bullet damage == Damage 
    void yourLogicalCode() 
    { 
     int someBulletDamage = 30; 
     if (someBulletDamage == Damage) 
     { 
      //Call the function 
      savedFunc.Invoke(); 
     } 
    } 
} 

使用

void Start() 
{ 
    Bullet bullet = new Bullet(30, myCallBackMethod); 
} 

void myCallBackMethod() 
{ 

} 
+1

只是一个补充。 OP还可以使用系统“代表”和“事件” – Cabrra

+1

@Cabrra是的,OP可以使用原始的'delegates'和'events'。只是OP想要将函数传递给一个函数,然后再调用它。** NOT **稍后调用一个事件。我认为'System.Action'或'Func'对于这个或者更少的代码来说更适合。 – Programmer

+1

优秀解释(也upvoted) – Cabrra

0

你需要在c#中调用委托, 首先你应该定义方法的输入/输出,然后你就像变量一样处理这种类型的方法。

public class Bullet 
{ 
public delegate void OnHit(bool something); 
public OnHit onHitMethod; 
public int Damage; 
public Bullet(int Damage, OnHit OnHit) 
{ 
    this.Damage = Damage; 
    this.onHitMethod = OnHit; 
} 
} 
在这一行 public delegate void OnHit(bool something);刚刚定义在这一行 public OnHit onHitMethod;所定义的方法,就像一个变量代表的类型和

相关问题