【发布时间】:2016-09-23 20:41:21
【问题描述】:
我需要用 C# 翻译/重写一些 C++ 代码。对于相当多的方法,写C++代码的人在原型中做过这样的事情,
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# 重写它。除非我使用指针和浸入不安全模式,否则我不确定如何执行此操作,因为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 的默认值,而且我不知道这个变量不会遇到哪些值。
我还研究了?? null-coalescing 运算符,但这似乎与我正在尝试做的相反。
我可以就我应该怎么做得到一些建议吗?
提前致谢。
【问题讨论】:
-
如果 y 是一个输出变量,可能使用 C# 的
out代替 ref。
标签: c# c++ null optional-parameters