[英]Correct use of Null-Conditional Operator with DateTime.Parse()
我正在尝试将字符串转换为DateTime?
仅在字符串不为null时使用DateTime.Parse()
。 我正在尝试使用空条件运算符
这是我要替换的内容:
string maxPermissableEndDate = response.Contract.ReferenceFields.FirstOrDefault(t => t.code == "MAX_EXT_DATE")?.Value;
if (!string.IsNullOrEmpty(maxPermissableEndDate))
{
contract.MaximumPermissableEndDate = DateTime.Parse(maxPermissableEndDate);
}
仅当变量maxPermissableEndDate不为null时, 才能以这种吸引人的方式分配可为空的DateTime属性MaximumPermissableEndDate?
这是我从C#6.0文档中看到的示例:
string result = value;
if (value != null) // Skip empty string check for elucidation
{
result = value.Substring(0, Math.Min(value.Length, length));
}
替代方案是:
value?.Substring(0, Math.Min(value.Length, length));
这不使用null合并运算符,而是类似的东西?
DateTime attemptParseDate;
contract.MaximumPermissableEndDate =
DateTime.TryParse(maxPermissableEndDate, out attemptParseDate)?
attemptParseDate : (DateTime?) null;
您可以执行以下操作:
contract.MaximumPermissableEndDate = string.IsNullOrEmpty(maxPermissableEndDate) ?
contract.MaximumPermissableEndDate
: new Nullable<DateTime>(DateTime.Parse(maxPermissableEndDate));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.