C# 为什么这条线没有';t work user.Age=(结果[11]==string.Empty)?(int?)null:Int32.Parse(结果[11])
假设C# 为什么这条线没有';t work user.Age=(结果[11]==string.Empty)?(int?)null:Int32.Parse(结果[11]),c#,conditional,code-snippets,ternary-operator,C#,Conditional,Code Snippets,Ternary Operator,假设result[11]==string.Empty(即result[11]='') System.FormatException未处理 Message=输入字符串的格式不正确。 Source=mscorlib 堆栈跟踪: 在System.Number.StringtonNumber(字符串str、NumberStyles选项、NumberBuffer和Number、>>>>NumberFormatInfo信息、布尔解析十进制) 在System.Number.ParseInt32(字符串s、Nu
result[11]==string.Empty
(即result[11]=''
)
System.FormatException未处理
Message=输入字符串的格式不正确。
Source=mscorlib
堆栈跟踪:
在System.Number.StringtonNumber(字符串str、NumberStyles选项、NumberBuffer和Number、>>>>NumberFormatInfo信息、布尔解析十进制)
在System.Number.ParseInt32(字符串s、NumberStyles样式、NumberFormatInfo信息)
在System.Int32.Parse处(字符串s)
对我来说,以上两个街区是相同的。那么为什么第一个有效而第二个无效呢?结果[i]可能会返回'object',ergo cast:
(string) result[i] == ....
Int.Parse( (string) result[i] )
这些区块不一样
if (result[11] == string.Empty) // this block works fine
{
user.Age = Int32.Parse(result[11]);
}
该块实际上不应该工作,因为该块将只解析空字符串。切换“if”块和“else”块中的代码,它将与三元“?:”运算符相同。您试图解析为整数的结果不是有效整数,因此会出现异常。 而是做下面的事情
if (!String.IsNullOrEmpty(result[11]))
{
if (!Int32.TryParse(result[11], out user.Age))
user.Age = null; // not really needed
}
我试过这个:
var value = "";
int? age;
if (value != string.Empty)
{
age = Int32.Parse(value);
}
else
{
age = null;
}
age = (value == string.Empty) ? (int?)null : Int32.Parse(value);
它工作得很好(我在第一个if中将
=
更改为!=
。每个人都回答了您如何将无效字符串解析为整数的问题。他们是对的。然而,显然人们没有注意到您的代码是不等价的,因为您颠倒了三元子句。这将是您的等效代码:
//if this is your code:
if (result[11] == string.Empty) // this block works fine
{
user.Age = Int32.Parse(result[11]);
}
else
{
user.Age = null;
}
//This is your equivalent ternary. You have inverted here
user.Age = (result[11] == string.Empty) ? Int32.Parse(result[11]) :
null;
您确定第一行不应该是if(result[11]!=string.Empty)吗?您应该选择string.IsNullOrEmpty()而不是mystring==string.Empty。错误出现在异常消息中:您正在解析无法解析的内容。可能该值为null,或者是非数字字符串?它们看起来不一样。这些操作是反向的,因为第一行应该是反向的!=not==,如果字符串[11]为null,而不是空的,则无法将null解析为int,因此就像Maud'Dib所说的,使用.IsNullOrEmpty()或使用ToString(),cast可能会失败(但是,可能您希望它失败),我认为这不是问题所在。Parse()需要一个字符串参数。如果result[]是一个对象数组,那么代码甚至无法编译……在这一点上,这两种方法都不起作用,因为他显然在试图解析一个无效的字符串@James Johnston,很公平,逻辑不正确,但他得到的异常是由他试图将无效字符串解析为整数引起的。我想结果[11]==string.Empty应该是空的=
//if this is your code:
if (result[11] == string.Empty) // this block works fine
{
user.Age = Int32.Parse(result[11]);
}
else
{
user.Age = null;
}
//This is your equivalent ternary. You have inverted here
user.Age = (result[11] == string.Empty) ? Int32.Parse(result[11]) :
null;