还有其他类似的帖子,但我正在努力寻找任何有意义的内容。对于 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/