在 VB 中,我对 DirectCast
和转换为值类型(double
、int
、...)有不同的行为,具体取决于间接数量
DirectCast(nothing, Double)
return 0
但是,如果我尝试将矩阵的元素转换为不等于任何东西,则会出现异常
Dim pArray as Object() = { nothing, 1.5, 2.27, -3.0}
DirectCast(pArray(1), Double) 'work with no issue
DirectCast(pArray(0), Double) 'Exception : Cannot convert to double
同理:
Dim TestCasting as object = nothing
Directcast(TestCasting, double) 'Exception : Cannot convert to double
如何使 pArray(0)
的 DirectCast
以与 DirectCast(nothing, double)
相同的方式工作?
我的帖子是一个突出问题的示例,无需担心其余代码。
要激动。这是一个可能会引起一些问题的例子。让我们拿一张随机表(没有主键或其他任何东西,但没关系):
TABLE [dbo].[IDENTIFICATION] (
[USER_ID] INT IDENTITY (1, 1) NOT NULL,
[PASSWORD] NVARCHAR(50) NULL,
[EXPIRATION_D] DATETIME NOT NULL,
[LAYOUT] INT NULL,
);
现在,我有一个返回 Object(,) 的方法
Dim pArray as Object(,) = myconnection.GetSqlRequest("Select USER_ID, PASSWORD, EXPIRATION_D, LAYOUT from IDENTIFICATION where USER_ID = 3")
这可能会返回类似于 { 3, "StackOverflow", New Date(2110,01,01), nothing}
的内容,因为布局是一个可选字段。
我可以这样做:
if pArray(0,3) is nothing then
Layout = 0
Else
Layout = DirectCast(pArray(0,3), Double)
End if
但我的目标是:
Layout = DirectCast(pArray(0,3))
主要是因为我正在重构我没有编写的代码的很大一部分,还因为它让我感到困扰,DirectCast(nothing, Double) 返回 0
除了这种情况。
最佳答案
这很简单:在数组中存储 Doubles
时不要使用 Nothing
并且在将 Object()
存储在数组中时不要使用 Object()
实际上想存储 double 。
等等,无论如何使用Double?()
会更好。可以使用 null/Nothing
初始化 Nullables 然后你根本不需要强制转换。
Dim pArray As Double?() = {Nothing, 1.5, 2.27, -3.0}
Dim first = pArray(0)
If first.HasValue Then
' No, it's a Nullable(Of Double)/Double? without a value
End If
编辑 根据您原来的问题。更好的问题是为什么这在 VB 中有效:
Dim d as Double = DirectCast(Nothing, Double) ' => 0.0
原因:VB.Net 中的 Nothing
等同于 C# 中的 default(T)
:给定类型的默认值,对于数字类型为 0, Date.MinValue
用于 Date
和 Nothing
(现在是 C# 中 null
的含义)用于引用类型。
因此 DirectCast(Nothing, Double)
将隐式转换为 Double
0。而 Object()
包含真正的对象,它是一切的占位符。但是 Nothing
通常是任何对象的“未知”状态,而不是 double,因此非常严格的 DirectCast
失败了。如果您将值 -3.0
更改为 -3
,它也会引发运行时错误,因为它实际上是一个 Integer
。
长话短说,
使用 CType
而不是 DirectCast
进行这些转换,它会起作用。
Dim obj As Object() = {Nothing, 1.0, 2}
Dim d1 = CType(obj(0), Double) ' => 0.0
Dim d2 = CType(obj(1), Double) ' => 1.0
Dim d3 = CType(obj(2), Double) ' => 2.0
关于vb.net - 什么都不转换到值类型 : different behavior depending on the number of indirection,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14121345/