c++空指针参数作为c#的可选参数
C++ null pointer argument as optional argument alternative in 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#中重写它时遇到了麻烦。除非我使用指针和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
的默认值,我不知道这个变量不会遇到哪些值。
我还研究了??
空合并操作符,但这似乎与我试图做的相反。
我可以得到一些建议,我应该做什么?
看起来你想要一个可选的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
也应该声明为可空,以匹配参数类型。然后将i
和j
作为它们传递给接收可为空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);
}
相关文章:
- 为什么会出现 gettnig 运行时错误:加载类型为"_Bit_type"(stl_bvector.h) 的空指针?
- 运行时错误:引用绑定到类型为"int"的空指针
- 这个失败的测试是将零添加到空指针未定义的行为、编译器错误还是其他什么?
- 为什么我在空指针错误(链表)中获取成员访问权限
- 从向量到空指针的 memcpy(反之亦然)不起作用
- 空指针常量 (nullptr)、空指针值和空成员指针值之间有什么区别?
- 可变参数函数指针的定义对于VxWorks spyLib来说不清楚
- 模板参数包指针的大小
- 成员访问是否在空指针上定义C++?
- 如何为C++字符串分配空指针参数?
- 如何检查谷歌模拟中作为空指针传递的字符串参数
- 作为参数的无名称空指针
- 如何正确地将一个文本整数作为参数作为空指针进行传递,并使用其地址作为整数的实际值
- 空指针参数,传递缓冲区
- 函数参数中的空指针与对象
- 使用空指针终止变量参数列表
- 如何使函数不使用STL容器参数(类似于空指针)
- c++空指针参数作为c#的可选参数
- 调试断言失败(无效空指针)默认字符串参数
- 函数参数中的空指针