我需要在C#中翻译/重写一些C++代码。对于相当多的方法,是谁写的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
的默认值,而且我不知道此变量不会遇到哪些值。
我也看过??
空合并运算符,但这似乎是我想要做的相反。
请问我该怎么办?
在此先感谢。
如果y是一个输出变量,也许使用C#的'out'而不是ref。 – Motes