我该怎么写
string date = "12/2/2011";
DateTime? dt = date ?? DateTime.Parse(date);
这会引发编译时错误。我知道我可以执行 tryparse 或执行 if {}
。有没有办法在一行中做到这一点?
最佳答案
尝试使用 conditional operator ?:
而不是 null-coalescing operator ??
:
DateTime? dt = date == null ? (DateTime?)null : DateTime.Parse(date);
您还需要将 null 转换为 DateTime?
否则会出现编译错误。
关于c# - 在一行中将字符串转换为 DateTime 可为空的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8347626/