c# - (可选)将结构传递给 C# 中的自定义函数

标签 c# struct null optional-parameters custom-function

还有其他类似的帖子,但我正在努力寻找任何有意义的内容。对于 C# 来说还是相当陌生...

所以,我想做的就是向自定义函数添加一个可选参数。这个参数需要包含两个值,所以我认为自定义结构可以工作,如下所示:

public struct FooBah {
    public string foo;
    public string bah;

    public FooBah(string foo, string bah) {
        this.foo  = foo;
        this.bah = bah;
    }
}

然后在函数调用中使用它:

FooBah foobah = new FooBah("foo", "bah");
CustomFunction(foobah);

对于函数本身:

private void CustomFunction(FooBah foobah = null) {
    if(foobah != null) {
        // Do something with foobah
    }
}

但是这个错误是因为:

A value of type '' cannot be used as a default parameter because there are no standard conversions to type 'FooBah'

请问有什么建议吗?

最佳答案

如果您可以检测到结构体的默认状态(例如 foo 为空),您可以编写如下代码:

static void CustomFunction(FooBah foobah = default)
{
    if (foobah.foo != null)
    {
        // Do something with foobah
    }
}

当然这取决于您对 foo 的使用情况.

或者您可以使用FooBah?参数:

static void CustomFunction(FooBah? foobah = null)
{
    if (foobah == null)
    {
        // Do something with foobah
    }
}

以下调用均有效:

CustomFunction();
CustomFunction(new FooBah());
CustomFunction(null);

var fooBah = new FooBah();
CustomFunction(fooBah);

请注意,如果您不想修改方法内的结构,可以使用 in修饰符:

static void CustomFunction(in FooBah? foobah = null)
{
    if (foobah == null)
    {
        Console.WriteLine("Default");
    }
    else
    {
        Console.WriteLine("Not default");
    }
}

请注意,使用可为空值类型时,您必须通过 .Value 访问该值本身属性(property),即 foobah.Value.foo - 这是因为类型是 Nullable<FooBah>而不是FooBah .

See here for the Nullable value type documentation

See here for more information什么时候应该使用in .

最后,最明显的解决方案是使用或不使用参数重载该方法。

关于c# - (可选)将结构传递给 C# 中的自定义函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/76217494/

相关文章:

c# - 使用 For 循环滑动对象 (C#)

c# - Visual Studio 2017 15.3 简化空检查

nullpointerexception - 为什么 HashMap.get 不返回可空类型?

c - 尝试将数据从一个结构复制到另一个结构时出现段错误

c - ISO C 禁止在 C 中使用空的初始化大括号

objective-c - 对象为零,除非我添加另一行 'random' 代码

c# - 无法使用实例引用访问成员 '<method>'

c# - 模型绑定(bind)到 Nancy 中的 Dictionary<string,string>

c# - 使用 Web API 访问查询字符串和表单参数

c++ - 初始化作为类成员的结构