Я занимался игровым движком, и часть его создала класс для элементов пользовательского интерфейса. Моя цель - сделать так просто добавить кнопки в пользовательский интерфейс с помощью только строки, которая будет включать расположение кнопки и какой метод она вызывает, когда кто-то нажимает эту кнопку. Я просто не могу понять, как передать целевой метод, который будет срабатывать при нажатии кнопки. Я могу получить методы для подписки на делегирование событий, просто не когда они завернуты в список объектов кнопок, которые я создал.
Я упростил код до того, чего я пытаюсь выполнить здесь. Главным моментом является то, что я не уверен, что вводить в качестве типа объекта для параметров метода для 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 "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);