简体   繁体   English

可为空的日期时间异常

[英]nullable date time exception

On respository, I have nullable string " o.Attribute("PreorderLanchDate")" converted to nullable datetime . 在存储库上,我将可空字符串" o.Attribute("PreorderLanchDate")"转换为nullable datetime

Here is the code: 这是代码:

PreorderLanchDate = o.Attribute("PreorderLanchDate") == null ? (DateTime?)null : DateTime.Parse(o.Attribute("PreorderLanchDate").Value), 

On controller, launchdate is nullable, not getting the value, as it is showing the null value exception. 在控制器上,launchdate是可为null的,无法获取值,因为它显示了null值异常。 here is the code: 这是代码:

LaunchDate = (DateTime)product.PreorderLanchDate

Try this. 尝试这个。

  //along with the null reference check, Use `String.IsNullOrEmpty` to check o.Attribute("PreorderLanchDate").Valuen
 PreorderLanchDate = o.Attribute("PreorderLanchDate") == null || String.IsNullOrEmpty(o.Attribute("PreorderLanchDate").Value) ? (DateTime?)null : DateTime.Parse(o.Attribute("PreorderLanchDate").Value), 



  //Cast to a nullable DateTime
LaunchDate = (DateTime?)product.PreorderLanchDate

product.PreorderLaunchDate是可为null的DateTime ,如果其值为null ,则将强制将其强制转换为正常的DateTime

You can use the as operator to perform certain types of conversions between compatible reference types or nullable types. 您可以使用as运算符在兼容的引用类型或可为空的类型之间执行某些类型的转换。

var nullableDateTime = product.PreorderLanchDate as DateTime;

if ( nullableDateTime != null )
    LaunchDate = nullableDateTime;

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

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