2016-09-23 40 views
3

我需要在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的默認值,而且我不知道此變量不會遇到哪些值。

我也看過??空合併運算符,但這似乎是我想要做的相反。

請問我該怎麼辦?

在此先感謝。

+0

如果y是一個輸出變量,也許使用C#的'out'而不是ref。 – Motes

回答

2

它像你想的可選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); 
} 
+0

但我認爲C++代碼並不打算通過引用傳遞,而C#引擎往往會這樣做。它需要一個指向int的指針,C#可以通過ref關鍵字來實現,但不能爲null。埃姆。 –

+0

C++代碼是「通過引用傳遞」,儘管在C++中引用或右值與指針之間存在區別。但是,C++代碼正在做C#調用通過引用傳遞的內容。'ref'和'out'都通過引用傳遞,但'out'只傳回,它不編組原始對象。 – Motes

+0

C++傳遞一個默認值爲NULL的指針。在檢查NULL的C++代碼中,現在只是總是假定它不是空值並返回值,那麼helper方法會在清理堆棧時將其丟棄。在你的C#代碼中,除非你想要返回值,否則不再傳遞值x,即當你不需要x時,不要傳遞'null'或任何東西。 – Motes

0

j應該聲明爲無效,以匹配參數類型。然後ij作爲它們被傳遞給你的函數,該函數接收一個可以爲空的int參數。

此外,您正在爲函數中的n賦值,因此無論您嘗試什麼,您的代碼總是會遇到not null大小寫。

這應該工作:

 public static int test(int? n) // without the keyword ref 
     { 
      int x = 10; 
      //n = 5; // Why was that?? 
      if (n != null) 
      { 
       Console.WriteLine("not null"); 
       n = x; 
       return 0; 
      } 
      Console.WriteLine("is null"); 
      return 1; 
     } 

     static void Main(string[] args) 
     { 

      int? i = null; // nullable int 
      int? j = 100; // nullable to match the parameter type 
      test(i); 
      test(j); 
      Console.WriteLine(i); 
     } 
+0

他想要ref關鍵字,我想。看起來像C++代碼試圖使用可選的輸入作爲一個可選的返回值。 – Motes