C ++空指针参数作为C#中的可选参数替代

时间:2016-09-23 20:41:22

标签: c# c++ null optional-parameters

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

如果我使用j方法中的变量main()取消注释行,则代码无法编译,并且表示类型int与类型int?不匹配。但无论哪种方式,这些方法将在稍后使用,int将被传递给它们,所以我并不是真的热衷于使用int?来保持兼容性。

我已经查看了C#中的可选参数,但这并不意味着我可以使用null作为int的默认值,而且我不知道这个变量不会有哪些值相遇。

我也调查了?? null-coalescing运算符,但这似乎与我正在尝试的相反。

我可以得到一些关于我该做什么的建议吗?

提前致谢。

2 个答案:

答案 0 :(得分: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);
}

答案 1 :(得分:0)

j也应声明为null,以匹配参数类型。然后,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);
        }