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

标签 c# c++ null optional-parameters

我需要用 C# 翻译/重写一些 C++ 代码。对于相当多的方法,编写C++代码的人在原型(prototype)中做了这样的事情,

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 的行,则代码不会编译并指出 intint? 类型不匹配。但无论哪种方式,这些方法将在以后使用,int 将传递给它们,所以我不太热衷于使用 int? 来保持兼容性。

我研究了 C# 中的可选参数,但这仍然不意味着我可以使用 null 作为 int 的默认值,而且我不知道哪个此变量不会遇到的值。

我还研究了 ?? 空合并运算符,但这似乎与我正在尝试做的相反。

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

提前致谢。

最佳答案

在我看来,您需要一个可选的 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++ 空指针参数作为 C# 中的可选参数替代,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39669210/

相关文章:

C# MVC Mock Model 通过接口(interface)打破了 Controller

c++ - MS 链接从 gnu make 失败,但从 cmd 行工作

Java : What happens when Connection object is nullified without calling Connection. 关闭()

C++ - 重复使用 istringstream

c++ - eclipse cpp ide 中的 uWebSockets undefined reference

javascript - 如何使用注入(inject)的 JavaScript 删除或覆盖页面上的函数?

c++ - 我如何在 C++ 中的字符串中嵌入 NULL 字符?

c# - 二十一点纸牌、字符串或整数的数组?

c# - 如何修复 : The provider did not return a ProviderManifestToken string?

c# - XSLT 选择模板