TryParse() 方法

处理数据时,你可能需要将字符串数据转换为数字数据类型。正如上一单元所述,由于字符串数据类型可以保留非数字值,因此将 string 转换为数字数据类型可能会导致运行时错误。

例如,以下代码:

string name = "Bob";
Console.WriteLine(int.Parse(name));

会导致以下异常:

System.FormatException: 'Input string was not in a correct format.'

若要避免格式异常,请对目标数据类型使用 TryParse () 方法。

使用 TryParse()

TryParse() 方法可同时执行多项操作:

我们可以使用 bool 对值执行操作(如执行一些计算),或在分析操作失败时显示一条消息。

备注

在此练习中,我们使用 int 数据类型,但对于所有数字数据类型,均可使用类似的 TryParse() 方法。

什么是 out 参数?

方法可返回值或返回 "void",后者意味着不返回值。方法还可以通过 out 参数返回值,这些值的定义与输入参数一样,但包含关键字 out

使用 out 参数调用方法时,还必须在变量前使用关键字 out,以便保存值。因此,在调用将用于存储 out 参数值的方法之前,必须先定义一个变量。然后,可在代码的其余部分使用包含 out 参数中包含的值。

步骤 1 - 将字符串 TryParse() 为 int

在 .NET 编辑器中,删除或注释掉前面练习中的所有代码,然后添加以下代码:

string value = "102";
int result = 0;
if (int.TryParse(value, out result))
{
    Console.WriteLine($"Measurement: {result}");
}
else
{
    Console.WriteLine("Unable to report the measurement.");
}

我们重点介绍下面这行代码:

if (int.TryParse(value, out result))

如果 int.TryParse() 方法成功地将 string 变量 value 转换为 int,则返回 true;否则,将返回 false。因此,将该语句置于 if 语句中,然后相应地执行决策逻辑。

请注意,转换后的值将存储在 int 变量 result 中。在此代码行之前声明并初始化了 int 变量 result,因此,对于属于 ifelse 语句的代码块,在其内部及外部均可访问该变量。

out 关键字指示编译器,TryParse() 方法不仅会以传统方式返回值(作为返回值),还会通过此双向参数传递输出。

运行代码时,应会看到以下输出:

Measurement: 102

步骤 2 - 稍后在代码中使用已分析的 int

为了演示之前已声明,并由 out 参数填充的 result 可在稍后的代码中使用,请在步骤 1 中编写的代码下方添加以下代码行:

// Since it is defined outside of the if statement,
// it can be accessed later in your code.
Console.WriteLine($"Measurement (w/ offset): {50 + result}");

整个代码段应与以下代码列表一致:

string value = "102";
int result = 0;
if (int.TryParse(value, out result))
{
    Console.WriteLine($"Measurement: {result}");
}
else
{
    Console.WriteLine("Unable to report the measurement.");
}

// Since it is defined outside of the if statement,
// it can be accessed later in your code.
Console.WriteLine($"Measurement (w/ offset): {50 + result}");

运行应用程序后,应会得到以下结果:

Measurement: 102
Measurement (w/ offset): 152

步骤 3 - 将字符串变量修改为不可分析的值

最后,我们来研究另一种情况,即我们故意为 TryParse() 提供不能转换为 int 的错误值。

修改第一行代码,将变量 value 重新初始化为其他值:

string value = "bad";

此外,请修改最后一行代码,先确保结果大于零,然后再显示第二条消息:

if (result > 0)
    Console.WriteLine($"Measurement (w/ offset): {50 + result}");

整个代码示例应与以下代码一致:

string value = "bad";
int result = 0;
if (int.TryParse(value, out result))
{
    Console.WriteLine($"Measurement: {result}");
}
else
{
    Console.WriteLine("Unable to report the measurement.");
}

// Since it is defined outside of the if statement,
// it can be accessed later in your code.
if (result > 0)
    Console.WriteLine($"Measurement (w/ offset): {50 + result}");

再次运行代码,应会得到以下结果:

Unable to report the measurement.

回顾

TryParse() 方法是一个非常有用的工具。下面是一些需要记住的便捷提示: