为什么int.TryParse无法初始化多个变量 [英] why int.TryParse cannot initialise multiple variables

查看:39
本文介绍了为什么int.TryParse无法初始化多个变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 int.TryParse 解析为变量(在数据库中另存为字符串),并且很好奇为什么我无法初始化2个变量:

I am using int.TryParse to parse to variables (saved as strings in the database) and am curious why I cannot initialise 2 variables:

int min, 
    max;

使用以下条件语句:

bool lengthCompatible = int.TryParse(string1, out min) &&
                        int.TryParse(string2, out max);

Visual Studio(2015)产生以下代码突出显示:

Visual Studio (2015) produces the following code highlighting:

使用未分配的局部变量"max"

Use of unassigned local variable 'max'

访问之前,本地变量'max'可能未初始化

Local variable 'max' might not be initialized before accessing

但是,如果我使用2条条件语句:

However, if I use 2 conditional statements:

bool minParse = int.TryParse(sentenceType.MinimumLength, out min);
bool maxParse = int.TryParse(sentenceType.MaximumLength, out max);

我可以毫无错误地进行编译.

I can compile with no errors.

越来越好奇!任何见解表示赞赏.

Curiouser and curiouser! Any insight appreciated.

欢呼

推荐答案

好,您正在使用&& ,如果 int.TryParse(string1,out min)返回 false ,不会再次调用 int.TryParse ,因此 max 是'肯定分配了.

Well you're using &&, which is short-circuiting... if int.TryParse(string1, out min) returns false, the second call to int.TryParse won't be made, so max isn't definitely assigned.

可以写:

if (int.TryParse(string1, out min) &&
    int.TryParse(string2, out max))
{
    // Use min and max here
}

...,因为如果两个调用都已执行,编译器就会知道只有到达 if 语句的主体.

... because then the compiler knows that you only reach the body of the if statement if both calls have been executed.

或者,您可以将非短路版本与& 一起使用,而不是&& :

Alternatively you could use the non-short-circuiting version with & instead of &&:

bool lengthCompatible = int.TryParse(string1, out min) &
                        int.TryParse(string2, out max);

这有点不寻常.上面的 if 版本的优点在于,您将保留&& 的性能优势,因为您无需费心尝试解析 string2(如果不需要).(当然,这完全取决于您要执行的操作.)

That's slightly unusual though. The advantage of the if version above is that you'll retain the performance benefit of &&, in that you won't bother trying to parse string2 if you don't need to. (It depends on exactly what you're trying to do, of course.)

这篇关于为什么int.TryParse无法初始化多个变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆