【问题标题】:C++ null pointer argument as optional argument alternative in C#C++ 空指针参数作为 C# 中的可选参数替代
【发布时间】: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


【解决方案1】:

在我看来,您需要一个可选的 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);
}

【讨论】:

  • 但我认为 C++ 代码并不打算通过引用传递,而 C# out 往往会这样做。它需要一个指向 int 的指针,而 C# 可以使用 ref 关键字来做到这一点,但不能为空。嗯。
  • C++ 代码是“通过引用传递”,尽管在 C++ 中存在引用或右值和指针之间的区别。但是,C++ 代码正在执行 C# 调用的按引用传递。 refout 都通过引用传递,但 out 只传递回来,它不会编组源对象。
  • C++ 正在传递一个默认值为 NULL 的指针。在它检查 NULL 的 C++ 代码中,现在总是假设它不为 null 并传回该值,然后辅助方法将在清理其堆栈时丢弃它。在您的 C# 代码中,除非您想要返回值 x,否则不再传递值 x,即当您不需要 x 时,根本不传递 null 或任何东西。
【解决方案2】:

j 也应声明为可空值以匹配参数类型。然后,ij 都应作为它们传递给接收可为 null 的 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);
        }

【讨论】:

  • 他想要 ref 关键字,我想。看起来 C++ 代码试图使用可选输入作为可选返回值。
猜你喜欢
  • 1970-01-01
  • 2017-11-28
  • 1970-01-01
  • 2013-09-12
  • 1970-01-01
  • 1970-01-01
  • 2015-09-13
  • 1970-01-01
相关资源
最近更新 更多