2016-09-23 104 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