c++空指针参数作为c#的可选参数

本文关键字:参数 空指针 c++ | 更新日期: 2023-09-27 18:08:29

我需要用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#中重写它时遇到了麻烦。除非我使用指针和dip不安全模式,否则我真的不确定如何做到这一点,因为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的默认值,我不知道这个变量不会遇到哪些值。

我还研究了??空合并操作符,但这似乎与我试图做的相反。

我可以得到一些建议,我应该做什么?

c++空指针参数作为c#的可选参数

看起来你想要一个可选的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);
}

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);
        }