gpt4 book ai didi

c# - 使用方法作为默认参数

转载 作者:行者123 更新时间:2023-11-30 17:58:38 29 4
gpt4 key购买 nike

我想在我的自定义 XNA GUI 中创建一个 Button 类,它接受方法作为参数,类似于 Python 的 tkinter 中的方式。你可以设置要调用的函数 Button.config(command = a_method) .

我读过有关使用委托(delegate)作为参数的信息 here , herehere ,但我似乎离它的工作还差得很远。我不完全理解代表是如何工作的,但我尝试了几种不同的方法都没有成功,比如使用 Func<int>? command = null为了以后测试看是否commandnull然后我会调用预设默认值,但随后我得到一个 Func cannot be nullable type或类似的东西。

理想情况下,代码应该是这样的:

class Button
{
//Don't know what to put instead of Func
Func command;

// accepts an argument that will be stored for an OnClick event
public Button(Action command = DefaultMethod)
{
if (command != DefaultMethod)
{
this.command = command;
}
}
}

但似乎我尝试过的一切都没有奏效。

最佳答案

默认参数必须是编译时常量。在 C# 中,委托(delegate)不能是常量。您可以通过在实现中提供自己的默认值来获得类似的结果。 (这里只是使用Winforms)

    private void button1_Click(object sender, EventArgs e)
{
Button(new Action(Print));
Button();
}

public void Button(Action command = null)
{
if (command == null)
{
command = DefaultMethod;
}
command.Invoke();
}

private void DefaultMethod()
{
MessageBox.Show("default");
}

private void Print()
{
MessageBox.Show("printed");
}

关于c# - 使用方法作为默认参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12097989/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com