我正在使用可以为空的DateTime对象并遇到一些奇怪的行为.这是一个示例函数:
public DateTime? Weird()
{
DateTime check = DateTime.Now;
DateTime? dt;
if (check == DateTime.MinValue)
dt = null;
else
dt = Viewer.ActiveThroughUTC.ToLocalTime();
//this line give a compile error
dt = (check == DateTime.MinValue) ? (null) : (Viewer.ActiveThroughUTC.ToLocalTime());
return dt;
}
Run Code Online (Sandbox Code Playgroud)
据我所知,三元运算符的行应与前四行相同,但VS2010给出了一个编译错误,说没有<null>和DateTime 之间存在转换(即使有问题的对象是'DateTime' ?').有什么我应该知道的关于三元运算符的东西还是这个(喘气?)一个错误?
只是一个虚构的代码,但为什么这不起作用?(因为date变量可以为空)
DateTime? date = textBoxDate.Text != "" ? textBoxDate.Text : null;
Run Code Online (Sandbox Code Playgroud)
错误是" System.DateTime和之间没有明确的转换<null>
我从SQL-Server检索一些日期时间数据.在我的Web.Api控制器中,我建议数据库数据到我的对象.
这有效:
if (reader["images_lastupload"] == DBNull.Value)
{
mydata.ImagesLastUpload = null;
}
else
{
mydata.ImagesLastUpload = Convert.ToDateTime(reader["images_lastupload"].ToString());
}
Run Code Online (Sandbox Code Playgroud)
db字段"Images_lastupload"可以为NULL.所以我想检查一下.
mydata.ImagesLastUpload是一个可以为空的日期时间.一切正常.
但是短版不起作用:
mydata.ImagesLastUpload = (reader["images_lastupload"] == DBNull.Value) ? null : Convert.ToDateTime(reader["images_lastupload"].ToString());
Run Code Online (Sandbox Code Playgroud)
如何使短版本工作?我的德语错误是:
Der Typ des bedingten Ausdrucks kann nicht bestimmt werden,weil keine implizite Konvertierung zwischen''und'System.DateTime'erfolgt.
可能重复:
可空类型和三元运算符.为什么这不起作用?
这是我的代码有效
public decimal? Get()
{
var res = ...
return res.Count() > 0 ? res.First() : (decimal?) null;
}
Run Code Online (Sandbox Code Playgroud)
这个不起作用
public decimal? Get()
{
var res = ...
return res.Count() > 0 ? res.First() : null;
}
Run Code Online (Sandbox Code Playgroud)
给出编译器错误:
错误1无法确定条件表达式的类型,因为'decimal'和'
<null>' 之间没有隐式转换
我想知道为什么?有任何想法吗?
为什么这不起作用?
DateTime? date = condition?DateTime.Now: null; //Error: no implicit conversion between DateTime and null
Run Code Online (Sandbox Code Playgroud)
这样做呢?
DateTime? date;
if (condition)
{
date = DateTime.Now;
}
else
date = null;
Run Code Online (Sandbox Code Playgroud)
这里可以找到一个类似的问题,但我无法进行关联.谢谢你的帮助..
更新:我阅读了Jon Skeet推荐的规范文档,它说:
If one of the second and third operands is of the null type and the type of the other is a
reference type, then the type of the conditional expression is that reference type
Run Code Online (Sandbox Code Playgroud)
那么,当使用三元运算符时,即使我已经指定了变量类型,也会强制进行转换?
我在使用?:运算符的方法中返回可空类型时遇到了一些困难.
例如,这有效:
public static Int32? RunInt32Query(string query, KeyValueCollection parameters)
{
object scalar = RunScalarQuery(query, parameters);
if (scalar != null)
{
return Convert.ToInt32(scalar);
}
else
{
return null;
}
}
Run Code Online (Sandbox Code Playgroud)
但是这个例子不起作用,它不会编译:
public static Int32? RunInt32Query(string query, KeyValueCollection parameters)
{
object scalar = RunScalarQuery(query, parameters);
return (scalar != null) ? Convert.ToInt32(scalar) : null;
}
Run Code Online (Sandbox Code Playgroud)
据我了解,这两种方法在高水平上几乎完全相同,但显然不是?