简体   繁体   English

如果+可空类型(C#)的简写

[英]Shorthand if + nullable types (C#)

The following returns 以下返回

Type of conditional expression cannot be determined because there is no implicit conversion between 'double' and '<null>' 无法确定条件表达式的类型,因为“double”和“<null>”之间没有隐式转换

aNullableDouble = (double.TryParse(aString, out aDouble) ? aDouble : null)

The reason why I can't just use aNullableBool instead of the roundtrip with aDouble is because aNullableDouble is a property of a generated EntityFramework class which cannot be used as an out par. 之所以我不能只使用aNullableBool而不是使用带有aDouble的往返是因为aNullableDouble是生成的EntityFramework类的一个属性,它不能用作超标。

aNullableDouble = double.TryParse(aString, out aDouble) ? (double?)aDouble : null;

Just blow the syntax out into the full syntax instead of the shorthand ... it'll be easier to read: 只需将语法吹成完整语法而不是速记......它会更容易阅读:

aNullableDouble = null;
if (double.TryParse(aString, out aDouble))
{
    aNullableDouble = aDouble;
}
aNullableDouble = (double.TryParse(aString, out aDouble)?new Nullable<double>(aDouble):null)

The interesting side-effect of using nullable types is that you can't really use a shorthand IF. 使用可空类型的有趣副作用是你不能真正使用速记IF。 Shorthand IF has to return the same Type from both conditions, and it can't be null in either case. 速记IF必须从两个条件返回相同的Type,并且在任何一种情况下都不能为null。 So, cast or write it out :) 所以,施放或写出来:)

.NET supports nullable types , but by declaring them as such you have to treat them a bit differently (as, understandably, something which is normally a value type now is sort of reference-ish). .NET支持可空类型 ,但是通过声明它们,你必须稍微区别对待它们(因为,可以理解的是,现在通常是值类型的东西是一种引用 - ish)。

This also might not help much if you end up having to do too much converting between nullable doubles and regular doubles... as might easily be the case with an auto-generated set of classes. 如果您最终必须在可空双打和常规双打之间进行太多转换,这也可能没有多大帮助......对于自动生成的类集合可能很容易。

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

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