c# - Action 作为函数中的可选参数

标签 c# action optional-parameters

<分区>

是否可以将 Action 作为函数中的可选参数? button2Action 应该是可选的。

public void DrawWindow(Rect p_PositionAndSize, string p_Button2Text = "NotInUse", Action p_Button2Action)
{
 // Stuff happens here
}

我用例如 p_Button2Action = delegate{ Debug.Log("NotInUse"); 试过了} 但它不会编译,因为 p_Button2Action 的默认参数值必须是编译时常量。如何制作一个编译时常量的可选 Action?

最佳答案

您必须为默认参数指定一个常量值,因此您可以为 Action 指定的唯一默认值是 null。

但是,检查 null 并替换正确的值很容易:

public void DrawWindow(Rect p_PositionAndSize, string p_Button2Text = "NotInUse", Action p_Button2Action = null)
{
    if (p_Button2Action == null)
        p_Button2Action = delegate{ Debug.Log("NotInUse"); }

    ...
}

关于c# - Action 作为函数中的可选参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17337083/

相关文章:

c# - 在 C# 中获取计算机名称而不引用 Microsoft.VisualBasic.dll

c# - 为什么我的客户端/服务器代码不能在我的本地机器之外工作?

javascript - 在 jQueryMobile 中使用表单提交处理程序进行验证,但阻止发送

python - 如何编译具有可变输入类型的 numba jit'ed 函数?

sql-server-2008 - SQL Server 存储过程中的可选参数

c# - 无法将 HttpStringContent 转换为 HttpContent

C#/.NET - 将字符代码转换为等效字符的方法

c# - 在 Silverlight 中同步操作

jquery - 更改表单的操作属性

r - 当内部函数参数依赖于可选参数时,R 中的参数传递