为什么不有条件的经营者正确地允许使用"零"用于分配给可空类型? [英] Why doesn't the conditional operator correctly allow the use of "null" for assignment to nullable types?

查看:208
本文介绍了为什么不有条件的经营者正确地允许使用"零"用于分配给可空类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  

可能显示的文件:
  <一href="http://stackoverflow.com/questions/858080/nullable-types-and-the-ternary-operator-why-wont-this-work">Nullable类型和三元运算符。为什么赢得&rsquo的;?吨这项工作
  <一href="http://stackoverflow.com/questions/75746/conditional-operator-assignment-with-nullablevalue-types">Conditional可空&LT运营商分配;价值&GT;类型?

这不能编译,指出有条件的前pression类型无法确定,因为没有'System.DateTime的'和''之间的隐式转换

  task.ActualEndDate = TextBoxActualEndDate.Text!=? DateTime.Parse(TextBoxActualEndDate.Text):空;
 

这只是正常工作

 如果(TextBoxActualEndDate.Text!=)
    task.ActualEndDate = DateTime.Parse(TextBoxActualEndDate.Text);
其他
    task.ActualEndDate = NULL;
 

解决方案

这不起作用,因为编译器不会一下子插入两侧的隐式转换,而需要一个隐式转换成为可空类型。

相反,你可以写

  task.ActualEndDate = TextBoxActualEndDate.Text!=?
    DateTime.Parse(TextBoxActualEndDate.Text):新的datetime();?
 

这仅需要一个隐式转换(的DateTime 日期时间?)。

另外,你可以施展任何左侧:

  task.ActualEndDate = TextBoxActualEndDate.Text!=?
    (日期时间?)DateTime.Parse(TextBoxActualEndDate.Text):空;
 

这也只需要一个隐式转换。

Possible Duplicates:
Nullable types and the ternary operator. Why won’t this work?
Conditional operator assignment with nullable<value> types?

This will not compile, stating "Type of conditional expression cannot be determined because there is no implicit conversion between 'System.DateTime' and ''"

task.ActualEndDate = TextBoxActualEndDate.Text != "" ? DateTime.Parse(TextBoxActualEndDate.Text) : null;

This works just fine

 if (TextBoxActualEndDate.Text != "")
    task.ActualEndDate = DateTime.Parse(TextBoxActualEndDate.Text);
else
    task.ActualEndDate = null;

解决方案

This doesn't work because the compiler will not insert an implicit conversion on both sides at once, and null requires an implicit conversion to become a nullable type.

Instead, you can write

task.ActualEndDate = TextBoxActualEndDate.Text != "" ? 
    DateTime.Parse(TextBoxActualEndDate.Text) : new DateTime?();

This only requires one implicit conversion (DateTime to DateTime?).

Alternatively, you can cast either left side:

task.ActualEndDate = TextBoxActualEndDate.Text != "" ? 
    (DateTime?)DateTime.Parse(TextBoxActualEndDate.Text) : null;

This also requires only one implicit conversion.

这篇关于为什么不有条件的经营者正确地允许使用&QUOT;零&QUOT;用于分配给可空类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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