我需要在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