.net - Decimal.ToDouble Vs CType(x, Double) 什么是推荐/首选

标签 .net vb.net casting double type-conversion

我的目标是转换 DecimalNumericUpDown 返回控制到 Double .

我可以使用

MyDouble = Convert.ToDouble(MyDecimal)

或者
MyDouble = CType(MyDecimal, Double)

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

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

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

最佳答案

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

您的问题的答案是“视情况而定”。例如,它在该页面上声明

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).

关于.net - Decimal.ToDouble Vs CType(x, Double) 什么是推荐/首选,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31943085/

相关文章:

c# - .NET 中的屏幕文本大小

c# - 为什么ConcurrentQueue提供TryPeek()和TryDequeue(),而Queue提供Peek()和Dequeue()?

vb.net - 如何删除这个 GoTo?

c# - 将字符串转换为枚举

c# - 转换值类型常量

c# - Windows Server 2008 R2 上的 WPF 样式

.net - Bitmap.SetPixel(x,y, Color) 太慢

.net - Textbox.text 绑定(bind)到 MySettings 不起作用

vb.net - GetPrivateProfileString() 返回空字符串,尽管有默认值

Haskell:具有逻辑上不同 bool 值的类型安全