如何将方法作为参数传递

本文关键字:参数传递 方法 | 更新日期: 2023-09-27 18:28:54

我一直在修改一个游戏引擎,其中一部分是为UI元素构建一个类。我的目标是让在UI中添加按钮变得非常简单,只需一行就可以包括按钮的位置以及当有人按下按钮时它调用的方法。我只是不知道如何传入按下按钮时将触发的目标方法。我可以获得订阅委托事件的方法,只是当它们被封装在我创建的按钮对象列表中时不行。

我已经将代码简化为我要在这里完成的内容。主要的症结在于,我不确定应该将什么作为addButton()方法参数的对象类型,以便能够传入另一个可以订阅委托事件的方法。如果我尝试Void或Object,我会得到转换错误。

public Class UserButton
{
    public delegate void triggerEvent();
    public triggerEvent ButtonPress; //This should fire off the event when this particular button is pressed.
    public UserButton(Point buttonlocation, Point buttonsize, string buttontext, Texture2d Texture)
    {
        //Store all this data
    }
}
public Class UserInterface  //This class is for the buttons that appear on screen.  Each button should have a location and a method that it calls when it's "pressed"
{
    List<UserButton> ButtonList = new List<UserButton>(); //List of all the buttons that have been created.  

        //Add a button to the list.
    public void addButton(Point location, Point buttonsize, Texture2d texture, Method triggeredEvent) //Compile fails here because I can't figure out what type of object a method should be.
    {
        UserButton button = new UserButton(Point location, Point buttonsize, Texture2d texture);
        button.ButtonPress += triggeredEvent; //The target method should subscribe to the triggered events. 
        ButtonList.Add(button);
    }
    public void checkPress(Point mousePos) //Class level method to sort through all the buttons that have been created and see which one was pressed.
    {
        foreach (UserButton _button in ButtonList)
        {
            if (_button.ButtonBounds.Contains(mousePos))
            {
                _button.ButtonPress(); //Call the event that should trigger the subscribed method.
            }
        }
    }
}
public class Game1 : Game
{
    //Main methods
    //Load
    protected override void LoadContent()
    {
        UI = new UserInterface(); //Create the UI object
        UI.addButton(new Point(32,32), Texture,toggleRun()); //Pass in the method this button calls in here.
    }   
    private void toggleRun() //The button should call this method to start and stop the game engine.
    {
        if (running)
        {
            running = false;
        } else {
            running = true;
        }

        protected override void Update(GameTime gameTime)
        {
            if (MouseClick) //simplified mouse check event
            {
                UI.checkPress(mousePos); //Pass the current mouse position to see if we clicked on a button.
            }
        }
    }

如何将方法作为参数传递

您的"triggeredEvent"参数应为相同的委托类型"triggerEvent":

public void addButton(Point location, Point buttonsize, Texture2d texture, triggerEvent triggeredEvent) 

要将方法作为参数传递,请使用方法名称而不调用它(只有当方法"toggleRun"没有任何重载方法,并且与"triggerEvent"委托的签名匹配时,这才会起作用):

UI.addButton(new Point(32,32), Texture, toggleRun);