如何将默认值初始化为 C#7 out 变量?
How to initialize default value to C#7 out variables?
我使用 TryParse
将字符串解析为数字。我需要一个解决方案来使用默认值初始化变量,所以当 TryParse 无法转换时,我得到我的默认值。
这是代码:
long.TryParse(input.Code, out long Code = 123);
//Error CS1525 Invalid expression term '='
我想严格使用C#7输出变量标准。
你做不到....NET 运行时不知道 "success" 或 "failure" 或 long.TryParse
的任何内容。它只知道 TryParse
有一个 bool
return 值,并且在 TryParse
完成后, out
变量将被初始化。 true
和"there is a good value in result
"和false
和"there is no good value in result
"之间没有必然的相关性。
为了清楚起见,您可以:
static bool NotTryParse(string s, out long result)
{
return !long.TryParse(s, out result);
}
现在呢?什么时候应该使用默认值?
虽然 out
参数本身不能采用默认值,但您可以在 C# 7 中使用单个表达式来实现您想要执行的操作。只需将 out
参数与三元表达式组合即可:
var code = long.TryParse(input.Code, out long result) ? result : 123;
我使用 TryParse
将字符串解析为数字。我需要一个解决方案来使用默认值初始化变量,所以当 TryParse 无法转换时,我得到我的默认值。
这是代码:
long.TryParse(input.Code, out long Code = 123);
//Error CS1525 Invalid expression term '='
我想严格使用C#7输出变量标准。
你做不到....NET 运行时不知道 "success" 或 "failure" 或 long.TryParse
的任何内容。它只知道 TryParse
有一个 bool
return 值,并且在 TryParse
完成后, out
变量将被初始化。 true
和"there is a good value in result
"和false
和"there is no good value in result
"之间没有必然的相关性。
为了清楚起见,您可以:
static bool NotTryParse(string s, out long result)
{
return !long.TryParse(s, out result);
}
现在呢?什么时候应该使用默认值?
虽然 out
参数本身不能采用默认值,但您可以在 C# 7 中使用单个表达式来实现您想要执行的操作。只需将 out
参数与三元表达式组合即可:
var code = long.TryParse(input.Code, out long result) ? result : 123;