我如何使用int.TryParsenullable int?
我试图做类似下面的事情,显然不能编译.
int? nr1 = int.TryParse(str1, out nr1) ? nr1 : null;
实现它的正确方法是什么?
Jon*_*nna 12
因为out必须是int你需要的东西:
int temp;
int? nr1 = int.TryParse(str1, out temp) ? temp : default(int?);
Run Code Online (Sandbox Code Playgroud)
请注意,我也使用default(int?)而不是null因为条件类型不会起作用.? (int?)temp : null或者? temp : (int?)null也会解决这个问题.
从C#7(VS Studio 2017)开始,您可以内联声明 temp
int? nr1 = int.TryParse(str1, out int temp) ? temp : default(int?);
Run Code Online (Sandbox Code Playgroud)
int.tryParse将更改引用的out变量,并返回一个boolean,true如果传递的参数可以解析为整数.
你是这样的:
int? int1;
int tempVal;
if (!int.TryParse(str1, out tempVal))
{
int1 = null;
}
else
{
int1 = tempVal;
}
Run Code Online (Sandbox Code Playgroud)