为什么这一行不起作用 user.Age = (result[11] == string.Empty) ? (int?) null : Int32.Parse(结果[11])
假设 result[11] == string.Empty
(即 result[11] = ""
)
if (result[11] == string.Empty) // this block works fine
{
user.Age = Int32.Parse(result[11]);
}
else
{
user.Age = null;
}
// the following line will throw exception
user.Age = (result[11] == string.Empty) ? (int?) null :
Int32.Parse(result[11]);
<块引用>System.FormatException 未处理 消息=输入字符串的格式不正确。 来源=mscorlib 堆栈跟踪: 在 System.Number.StringToNumber(String str, NumberStyles options, NumberBuffer& number, >> >> NumberFormatInfo info, Boolean parseDecimal) 在 System.Number.ParseInt32(String s, NumberStyles 样式, NumberFormatInfo 信息) 在 System.Int32.Parse(String s)
对我来说,上面两个块是相同的。那么为什么第一个有效而第二个无效呢?
Assume result[11] == string.Empty
(i.e. result[11] = ""
)
if (result[11] == string.Empty) // this block works fine
{
user.Age = Int32.Parse(result[11]);
}
else
{
user.Age = null;
}
// the following line will throw exception
user.Age = (result[11] == string.Empty) ? (int?) null :
Int32.Parse(result[11]);
System.FormatException was unhandled
Message=Input string was not in a correct format.
Source=mscorlib
StackTrace:
at System.Number.StringToNumber(String str, NumberStyles options, NumberBuffer& number, >> >> NumberFormatInfo info, Boolean parseDecimal)
at System.Number.ParseInt32(String s, NumberStyles style, NumberFormatInfo info)
at System.Int32.Parse(String s)
To me, the above two blocks are same. Then why the first one works while the second one doesn't?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
块不一样。
该块实际上不应该工作,因为该块只会解析空字符串。切换“if”块和“else”块中的代码,它将与三元“? :”运算符相同。
The blocks are not the same.
That block should actually not work, because the block will only parse an empty string. Switch the code in the "if" block and the "else" block, and it will be identical to your ternary "? :" operator.
我已经尝试过这个:
它工作正常(我已将第一个 if 中的
==
更改为!=
)。I have tried this:
and it works fine (I have changed the
==
to!=
in the first if).您尝试解析为整数的结果不是有效的整数,因此会出现异常。
而是执行以下操作。
The result that you are trying to parse as Integer is not a valid Integer, hence the exceptions.
Rather do the following.
每个人都回答了您如何尝试将无效字符串解析为整数。他们是对的。然而,显然人们忽略了你的代码是不等价的,因为你颠倒了三元子句。这将是您的等效代码:
Everyone answered how you are trying to parse invalid strings as integer. They are right. However, apparently people have missed that your code is not equivalent, because you have inverted the ternary clauses. This would be your equivalent code:
result[i] 可能返回“object”,因此强制转换:
result[i] might return 'object', ergo cast: