简体   繁体   English

三元运算符意外结果

[英]Ternary Operator Unexpected Result

Can someone comment on the issue I'm having. 有人可以就我遇到的问题发表评论。 A ternary operator throws an error and the argument here is that if it evaluates to null then it should ignore the part after the colon. 三元运算符抛出一个错误,这里的参数是,如果它的计算结果为null,那么它应该忽略冒号后的部分。 The Watch set up for this indicates an exception: Watch为此设置表示异常:

Int32.Parse(SQLDataReader["TrayId"].ToString())' threw an exception of Type 'System.FormatException

suggesting that it can't convert a null to a string. 建议它不能将null转换为字符串。 Is this how it works? 这是怎么回事?

ShipmentId = SQLDataReader["ShipmentId"] == DBNull.Value ? 0 : Int32.Parse(SQLDataReader["ShipmentId"].ToString()),

The column ShipmentId is an integer, but it is also nullable , which means that the c# type is int? ShipmentId列是一个整数,但它也可以为nullable ,这意味着c#类型是int? .

The error boils down to this code: 错误归结为此代码:

Int32.Parse((string)null)

The parsing gives up because you can't turn null into an int . 解析因为你不能将null转换为int而放弃。

To fix this, use TryParse . 要解决此问题,请使用TryParse

int ShipmentId = 0;
int.TryParse(SQLDataReader["ShipmentId"].ToString(), out ShipmentId);

This will cover if the value is null , or if for some strange reason the value can't actually be converted to an int (like "asdf121343fds"). 这将覆盖如果值为null ,或者由于某些奇怪的原因,该值实际上不能转换为int(如“asdf121343fds”)。

建议与DBNull进行比较,使用DBNull.Value.Equals方法,如本页所述: http//msdn.microsoft.com/en-us/library/system.dbnull.value.aspx

ShipmentId = DBNull.Value.Equals(SQLDataReader["ShipmentId"]) ? 0 : Int32.Parse(SQLDataReader["ShipmentId"].ToString());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM