kbv*_*hnu 0 .net c# type-conversion .net-4.5
有没有办法转换这个?
public int? intVal ;
public double? dblVal ;
Run Code Online (Sandbox Code Playgroud)
我现在的工作方式
if(dblVal==null)
intVal =null;
else
intVal = Convert.ToInt32(dblVal);
Run Code Online (Sandbox Code Playgroud)
还有其他办法吗?提前致谢 .
Jon*_*eet 15
刚演员:
intVal = (int?) dblVal;
Run Code Online (Sandbox Code Playgroud)
This will already result in a null value if dblVal is null. Note that unlike Convert.ToInt32(double), this does not result in an exception if dblVal is outside the range of int. If that's a concern, you should work out exactly what you want to achieve.
From the C# 5 spec, section 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:
- S的显式转换?到T?.
- 从S到T的显式转换?
- S的显式转换?对T.
基于从S到T的基础转换的可空转换的评估进行如下:
- 如果可空转换来自S?到T?:
- 如果源值为null(HasValue属性为false),则结果为类型T?的空值.
- 否则,转换被评估为从S展开?到S,然后是从S到T的底层转换,接着是从T到T?的包装.
- ...
| 归档时间: |
|
| 查看次数: |
208 次 |
| 最近记录: |