TryParse()返回什么值?

时间:2015-05-29 06:03:36

标签: c# tryparse

我正在阅读这本书Fundamentals of Computer Programming with C#

string str = Console.ReadLine();
int Value;  
bool parseSuccess = Int32.TryParse(str, out Value);
Console.WriteLine(parseSuccess ? "The square of the number is " + (Value * Value) + " . "  : "Invalid number!" );

所以我的问题是,在第三行bool parseSuccess = Int32.TryParse(str, out Value); Int32.TryParse()不会返回int值?怎么可能bool?关键字out究竟是什么意思?

3 个答案:

答案 0 :(得分:6)

Int32.TryParse返回一个布尔值来指示解析是否成功(如果字符串包含非数字字符,则转换将失败)。

out表示参数通过引用传递(这意味着传递给TryParse函数的是变量的内存地址)。

答案 1 :(得分:2)

正如方法所说,TryParse,这意味着它是否能够解析,而这就是布尔值所指示的。

True:成功解析,并且可以从out参数中检索解析后的值。

错误:无法将字符串值解析为int。它不是抛出任何异常,而是告诉你使用这个布尔标志,在这种情况下你可以使用out param的默认值(whihch为0)或者指定你选择的其他值,如下所示:

int intValue = int.TryParse(stringValue, out intValue) ? intValue : myDefaultValue;//mydefaultValue is int containing value of your choice

int.TryParse syntatic sugar

How the int.TryParse actually works

答案 2 :(得分:2)

您的部分问题似乎是:

  

为什么TryParse定义为bool TryParse(string, out int)而不是int TryParse(string, out bool)

原因是所选择的签名允许这种常见模式:

int x;
if (int.TryParse(s, out x))
    Console.WriteLine(x); //or do whatever else

使用其他签名,我们需要这样做:

bool success;
int x = int.TryParse(s, out success);
if (success)
    Console.WriteLine(x); // or do whatever else

第一个更简洁,显然,根据我的经验,至少,大多数TryParse调用直接用于流控制,而不是将返回值赋给变量。