[英]Is it possible that a C# method parameter of some kind of int can accept null and can update argument
As below code expressed, I want SomeMethod 如下面的代码所示,我想要SomeMethod
if parameter is none null, it will use it's value, then update the value of argument variable in Caller2 如果parameter不为null,它将使用它的值,然后更新Caller2中参数变量的值
void Caller1() { SomeMethod(null, ...); } void Caller2() { int argument = 123; SomeMethod(argument, ...); Debug.Assert(argument == 456); } void SomeMethod(SomeKindOfInt parameter, ...) { if (parameter != null) { // use the value of parameter; parameter = 456; // update the value of argument which is in Caller2 } }
Tried and declare: 尝试并声明:
Almost there, you can use int?
快到了,可以使用int?
to allow null value and put the ref
keyword. 以允许为空值并放置ref
关键字。
static void Main(string[] args)
{
int? test1 = null;
SomeMethod(ref test1);
Console.WriteLine(test1);
// Display 456
int? test2 = 123;
SomeMethod(ref test2);
Console.WriteLine(test2);
// Display 123
Console.ReadLine();
}
static void SomeMethod(ref int? parameter)
{
if (parameter == null)
{
parameter = 456;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.