如何正确处理System.Nullable< T>LinqToSql类的字段? [英] How to correctly deal with System.Nullable<T> fields of LinqToSql classes?
问题描述
我有一个带有一些可为null的double字段的表.与LinqToSQL一起尝试直接使用该字段,我得到了
I've got a table with some nullable double fields. Working with LinqToSQL trying to use the field directly I get
参数类型System.Nullable不能分配给参数类型double
Argument type System.Nullable is not assignable to parameter type double
我该如何正确处理?
推荐答案
问题与Linq无关.这与 double
和 double?
/ Nullable< double>
之间的转换有关.
The problem has nothing to do with Linq. It's got to do with conversion between double
and double?
/Nullable<double>
.
不允许从 double?
到 double
的隐式转换:
Implicit conversion from double?
to double
is not allowed:
double? foo ;
double bar = foo ;
-
您可以直接引用double值:
You can reference the double value directly:
double? foo ; double bar = foo.Value ;
如果
Nullable< T>
为null(即.HasValue
为false),则会抛出NullReferenceException
.This will throw a
NullReferenceException
if theNullable<T>
is null (that is,.HasValue
is false).您可以投射它:
double? foo ; double bar = (double) foo ;
同样,如果
Nullabl< T>
为null,则会出现异常.Again, you'll get an exception if the
Nullabl<T>
is null.如果
Nullable< T>
为null,则可以使用null合并运算符分配默认值: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? I don't know. It depends on your context.
这篇关于如何正确处理System.Nullable< T>LinqToSql类的字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!