2012-09-14 62 views
3

我目前正在和一个老的api做斗争,而且我面临以下问题:当我尝试将对象数组强制转换为对象数组时,我得到了运行时异常日期。将对象强制转换为可空对象的对象()

Module Module1 
    Sub Main() 
     Console.WriteLine(Misc.dateCast(New Nullable(Of DateTime)())) 
     Console.WriteLine(Misc.tabledateCast(New Nullable(Of DateTime)() {New DateTime()})) 
    End Sub 
End Module 

Module Misc 
    Function dateCast(ByVal val As Nullable(Of DateTime)) As Object 
     Return CType(val, Object) 
    End Function 

    Function tabledateCast(ByVal val As Object) As Object() 
     Return CType(val, IEnumerable(Of Object)).Cast(Of Object).ToArray 
    End Function 
End Module 

第一个演员正在工作,但不是第二个。如何成功投射到对象数组?我不能使用CType(val, IEnumerable(Of Nullable(Of DateTime))),因为函数可能会得到其他类型的数组。

+1

检查[这](HTTP://计算器.COM /问题/ 4632313/CAS t-object-to-ienumerableobject)答案。显然你可以投到'IEnumerable'而不是通用版本。 – Laoujin

回答

2

看起来你有两个选择:

1)如果这种阵列本身是类型安全的,可以泛化的方法,以便它知道铸造一个对象之前投什么 - 不是最好的代码看,特别是在VB.NET:

Module Module1 
    Sub Main() 
     Console.WriteLine(Misc.tabledateCast(Of Nullable(Of DateTime))(New Nullable(Of DateTime)() {New DateTime()})) 
    End Sub 
End Module 

Module Misc 
    Function tabledateCast(Of T)(ByVal val As Object) As Object() 
     Return CType(val, IEnumerable(Of T)).Cast(Of Object).ToArray 
    End Function 
End Module 

2)Laoujin的链接,在你做一个非通用IEnumerable投第一:

Module Module1 
    Sub Main() 
     Console.WriteLine(Misc.tabledateCast(New Nullable(Of DateTime)() {New DateTime()})) 
    End Sub 
End Module 

Module Misc 
    Function tabledateCast(ByVal val As Object) As Object() 
     Return CType(val, IEnumerable).Cast(Of Object).ToArray 
    End Function 
End Module