替代方式转换 int ?加倍?

Alternative way convert int ? to double?

有什么办法可以转换吗?

public int? intVal ;
public double? dblVal ;

我现在的工作情况

if(dblVal==null)
    intVal =null;
else
    intVal = Convert.ToInt32(dblVal);

还有其他方法吗?提前致谢。

刚投:

intVal = (int?) dblVal;

如果 dblVal 为空,这将已经产生 null 值。请注意,与 Convert.ToInt32(double) 不同,如果 dblVal 超出 int 的范围,这 不会 导致异常。如果这是一个问题,您应该准确地计算出您想要实现的目标。

来自 C# 5 规范,第 6.2.3 节:

Explicit nullable conversions permit predefined explicit conversions that operate on non-nullable value types to also be used with nullable forms of those types. For each of the predefined explicit conversions that convert from a non-nullable value type S to a non-nullable value type T (§6.1.1, §6.1.2, §6.1.3, §6.2.1, and §6.2.2), the following nullable conversions exist:

  • An explicit conversion from S? to T?.
  • An explicit conversion from S to T?.
  • An explicit conversion from S? to T.

Evaluation of a nullable conversion based on an underlying conversion from S to T proceeds as follows:

  • If the nullable conversion is from S? to T?:
    • If the source value is null (HasValue property is false), the result is the null value of type T?.
    • Otherwise, the conversion is evaluated as an unwrapping from S? to S, followed by the underlying conversion from S to T, followed by a wrapping from T to T?.
  • ...

方法如下:

intVal = dblVal.HasValue ? Convert.ToInt32(dblVal.Value) : (int?)null;