简体   繁体   English

如何在类中保存一个方法以便稍后执行

[英]How to save a method in a class to be executed later

I need to know how to pass a method into a class constructor so that it can be called later. 我需要知道如何将方法传递给类构造函数,以便以后可以调用它。 The idea is to have a Bullet class that has two properties, a damage integer and a Method that can be called when a bullet of that type has hit an object. 我们的想法是让一个Bullet类具有两个属性,一个损坏整数和一个可以在该类型的子弹击中一个对象时调用的方法。 The code below should explain a bit better: 下面的代码应该更好地解释一下:

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

This is so I can make bullets that preform different tasks upon impact by running something like Bullet.OnHit(HitGameObject). 这样我就可以通过运行Bullet.OnHit(HitGameObject)之类的东西来制作可以在影响时执行不同任务的项目符号。

You can use Action to pass a function to a function then store it in another Action . 您可以使用Action将函数传递给函数,然后将其存储在另一个Action The function that is stored can be called with Action.Invoke() . 可以使用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();
        }
    }
}

Usage : 用法

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

void myCallBackMethod()
{

}

What you need is called delegates in c#, First you should define method input/output and then you work with methods of this type just like variables. 你需要的是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;
}
}

in this line public delegate void OnHit(bool something); 在这一行public delegate void OnHit(bool something); you just defined the type of delegate and in this line public OnHit onHitMethod; 你刚刚定义了委托的类型,并在这行public OnHit onHitMethod; you defined the method just like a variable. 你定义的方法就像一个变量。

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

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