十进制转换?翻番? [英] Convert decimal? to double?

查看:147
本文介绍了十进制转换?翻番?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道什么是最好的方式(以更安全,更简洁的意义上)从一种可空类型转换为另一种兼容可空类型。

I am wondering what would be the best way (in the sense of safer and succinct) to convert from one nullable type to another "compatible" nullable type.

具体而言,从十进制转换?翻番?

Specifically, converting from decimal? to double? can be done using:

public double? ConvertToNullableDouble(decimal? source)
{
    return source.HasValue ? Convert.ToDouble(source) : (double?) null;
}



有没有更好的方式来做到这一点?也许利用一个标准的转换?

Is there any better way to do this? Maybe leveraging a standard conversion?

推荐答案

建于石膏为赢!就在VS2012的测试这和的VS2010:

Built in casts for the win! Just tested this in VS2012 and VS2010:

 decimal? numberDecimal = new Decimal(5); 
 decimal? nullDecimal = null;
 double? numberDouble = (double?)numberDecimal; // = 5.0
 double? nullDouble = (double?)nullDecimal;     // = null

只需使用一个明确的投会投空为null,内部十进制值双。成功了!

Just using an explicit cast will cast null to null, and the internal decimal value to double. Success!

这篇关于十进制转换?翻番?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆