如何将方法作为参数传递?

时间:2014-11-03 23:33:44

标签: c# methods delegates

我一直在修改游戏引擎,其中一部分已经为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.
            }
        }
    }

1 个答案:

答案 0 :(得分:2)

你的&#34; triggeredEvent&#34;参数应该是相同的委托类型&#34; triggerEvent&#34;:

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

要传递方法作为参数,请使用方法名称而不调用它(这仅在方法&#34; toggleRun&#34;没有任何重载方法时才有效,并且匹配&#34的签名; triggerEvent&#34; delegate):

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