I have a class in C# named Button
and I want the Button
have a functionality that can be passed through its constructor and whenever the Button
was pressed the Action
executes.
Button(Rect rect, string text, Action Func);
I have used Action
and It worked perfectly until I found out that I can't pass a void Action
with arguments.
For example:
void DoSomething(string str);
How can I be able to pass any void Action
with any arguments?
The button doesn't have to care about the argument, but it still needs to be passed a delegate with no arguments and returning void. This is easily done:
new Button(rect, text, () => YourMethod(whateverArgument))
Depending on what you're trying to do, whateverArgument
can be a local, a constant or a field. Just think about when it's supposed to read the value to pass to the inner method.
确保可以传递参数,只需使用以下命令:
Button b = new Button(.., .., () => DoSomething("YourString");
I advice you to use simplefied command pattern : Create base class or interface Command
interface ICommand
{
void Execute();
}
//Create secific command and pass parameters in constructor:
class Command : ICommand
{
public Command(string str)
{
//do smth
}
void Execute()
{
//do smth
}
}
Button(Rect rect, string text, ICommand cmd)
{
cmd.Execute();
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.