如何正确对待System.Nullable&LT; T&GT; LinqToSql类的领域? [英] How to correctly deal with System.Nullable<T> fields of LinqToSql classes?
问题描述
我有一些可为空双字段的表。与LinqToSQL试图直接使用我已经得到了外地打工参数类型System.Nullable不是分配给参数类型双。如何处理这是否正确?
I've got a table with some nullable double fields. Working with LinqToSQL trying to use the field directly I've got the "Argument type System.Nullable is not assignable to parameter type double". How to deal with this correctly?
推荐答案
问题无关使用LINQ。它有什么关系之间的转换双
和一倍
/ 可空&LT;双&GT;
。
The problem has nothing to do with Linq. It's got to do with conversion between double
and double?
/Nullable<double>
.
这是隐式转换一倍
到双
是不允许的:
Implicit conversion from double?
to double
is not allowed:
double? foo ;
double bar = foo ;
-
您可以直接引用的双重价值:
You can reference the double value directly:
double? foo ; double bar = foo.Value ;
这将抛出一个
的NullReferenceException
如果可空&LT; T&GT;
为空(即.HasValue
是假的)。This will throw a
NullReferenceException
if theNullable<T>
is null (that is,.HasValue
is false).您可以将它转换:
double? foo ; double bar = (double) foo ;
此外,你会得到一个异常,如果
Nullabl&LT; T&GT;
为null您可以使用空合并运算符来指定一个默认值,如果
可空&LT; T&GT;
为空:You can use the null coalescing operator to assign a default value if the
Nullable<T>
is null:double? foo ; double bar = foo ?? -1.0 ;
这,natch,避免了NullReferenceException`问题。
This, natch, avoids the NullReferenceException` problem.
您可以使用三元运营商同样的空合并运算符:
You can use the ternary operator in the same vein as the null coalescing operator:
double? foo ; double bar = ( foo.HasValue ? foo.Value : -2 ) ;
-
最后,你可以使用常规的条件逻辑遵循另一条路径:
Finally, you can use regular conditional logic to follow an alternative path:
double? foo ; double bar ; if ( foo.HasValue ) { doSomething(foo.Value) ; } else { doSomething() ; }
这些都是有关的选项。这是正确的?说不上来。依赖于上下文。
Those are about the options. Which is correct? Dunno. Depends on the your context.
这篇关于如何正确对待System.Nullable&LT; T&GT; LinqToSql类的领域?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!