转换小数? 加倍?

我想知道从一个可空类型转换为另一个“兼容”可空类型的最佳方式(在更安全和简洁的意义上)是什么。

具体来说,从十进制转换? 加倍? 可以使用:

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

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

为胜利而建造的演员阵容! 刚刚在VS2012 VS2010中进行了测试:

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

只使用显式强制转换会将null转换为null,并将内部十进制值转换为double。 成功!

通常,如果您希望从任何数据类型转换为另一种数据类型,只要它们兼容,请使用:

  Convert.ChangeType(your variable, typeof(datatype you want convert to)); 

例如:

  string str= "123"; int value1 = (int)Convert.ChangeType(str, typeof(int)); float? value2 = (float?)Convert.ChangeType(str, typeof(float)); ................................... 

再进一步,如果你想让它更安全,你可以添加一个try catch:

 string str= "123"; try { int value1 = (int)Convert.ChangeType(str, typeof(int)); int? value2 = (int?)Convert.ChangeType(str, typeof(int)); float value3 = (float)Convert.ChangeType(str, typeof(float)); float? value4 = (float?)Convert.ChangeType(str, typeof(float)); } catch(Exception ex) { // do nothing, or assign a default value } 

这是在VS 2010下测试的