我需要用 C# 翻译/重写一些 C++ 代码。对于相当多的方法,编写C++代码的人在原型(prototype)中做了这样的事情,
float method(float a, float b, int *x = NULL);
然后在方法中是这样的,
float method(float a, float b, int *x) {
float somethingElse = 0;
int y = 0;
//something happens here
//then some arithmetic operation happens to y here
if (x != NULL) *x = y;
return somethingElse;
}
我已经确认 x
是该方法的可选参数,但现在我在用 C# 重写它时遇到了问题。除非我使用指针和 dip 不安全模式,否则我不确定如何执行此操作,因为 int
不能为 null
。
我试过这样的,
public class Test
{
public static int test(ref int? n)
{
int x = 10;
n = 5;
if (n != null) {
Console.WriteLine("not null");
n = x;
return 0;
}
Console.WriteLine("is null");
return 1;
}
public static void Main()
{
int? i = null;
//int j = 100;
test(ref i);
//test(ref j);
Console.WriteLine(i);
}
}
如果我在 main()
方法中取消注释带有变量 j
的行,则代码不会编译并指出 int
与 int?
类型不匹配。但无论哪种方式,这些方法将在以后使用,int
将传递给它们,所以我不太热衷于使用 int?
来保持兼容性。
我研究了 C# 中的可选参数,但这仍然不意味着我可以使用 null
作为 int
的默认值,而且我不知道哪个此变量不会遇到的值。
我还研究了 ??
空合并运算符,但这似乎与我正在尝试做的相反。
我能得到一些关于我应该做什么的建议吗?
提前致谢。
最佳答案
在我看来,您需要一个可选的 out
参数。
我会在 C# 中使用重写。
public static float method(float a, float b, out int x){
//Implementation
}
public static float method(float a, float b){
//Helper
int x;
return method(a, b, out x);
}
关于c# - C++ 空指针参数作为 C# 中的可选参数替代,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39669210/