Decimal.ToDouble VS CType(x, Double) 什么是 recommended/preferred

Decimal.ToDouble Vs CType(x, Double) What is recommended/preferred

我的目标是将从 NumericUpDown 控件返回的 Decimal 转换为 Double

我可以用

MyDouble = Convert.ToDouble(MyDecimal)

MyDouble = CType(MyDecimal, Double)

或者,根据 MSDN Decimal 有一个 ToDouble 方法,所以我想:

MyDouble = MyDecimal.ToDouble

什么是 preferred/recommended 方法,为什么最后一个选项会给我一个未指定参数的错误?

WRT 这个问题的第一部分,如果应该对不同类型的对象使用不同的转换方法,是否有某个地方(最好是 MSDN)可以提供关于哪种方法的信息object/requirement可以参考?

就效率而言,CType 并不是最好的。 使用 Convert.ToDouble() 更容易被接受,因为它通常更有效。

如上评论所述,.ToDouble 是共享方法,因此您必须:

    Dim test As Decimal = 2.22
    Dim myDouble As Double

    myDouble = Convert.ToDouble(test)

    myDouble = Decimal.ToDouble(test)

以上任何一种方法都可以更改类型。

可能值得一读的是 this page on MSDN(转换函数、CType、DirectCast 和 System.Convert 部分)。

您问题的答案是 "It depends"。例如,它在该页面上声明

The exact method call or IL instructions generated depends on the expression against which the conversion is being applied. Some conversions are optimized away, such as CInt(123.45) which is replaced with the integer constant 123 in the IL. This is an example where using the Visual Basic Runtime results in better performance than using the System namespace

但是它最后的推荐却是:

Recommendation: For most conversions, use the intrinsic language conversion keywords (including CType) for brevity and clarity and to allow compiler optimizations when converting between types. Use DirectCast for converting Object to String and for extracting value types boxed in Object variables when the embedded type is known (that is, coercion is not necessary).