我可以在盒裝內置vb.net類型上成功使用CStr()
。但我如何才能實現與盒裝自定義類型相同?我越來越如何使CStr()處理盒裝自定義數據類型?
Exception thrown: 'System.InvalidCastException' in Microsoft.VisualBasic.dll
的codez:
' sample custom type
Structure Record
Public Property Value As Integer
Overloads Function TOSTRING() As String ' capitalizaition intentional to reveal usage
Return ">>" & Value.ToString() & "<<"
End Function
Shared Operator &(left As String, right As Record) As String
Return left & right.TOSTRING()
End Operator
Shared Widening Operator CType(left As Record) As String
Return left.TOSTRING()
End Operator
End Structure
' both use cases
Sub Main()
' demo with built-in type
Dim i As Integer = 3
Dim ib As Object = i ' boxed into Object
Debug.Print("i:" & CStr(i))
Debug.Print("ib:" & CStr(ib)) ' works OK
' demo with custom type
Dim r As New Record With {.Value = 3}
Dim rb As Object = r ' boxed into Object
Debug.Print("r:" & CStr(r))
Debug.Print("rb:" & CStr(rb)) ' Exception thrown:
' 'System.InvalidCastException' in Microsoft.VisualBasic.dll
End Sub
改用'.ToString()'。 –
@RezaAghaei - 不會無縫處理空值。相反,我想讓我的類型看起來像運行時的「本地」。也許我只是錯過了一些明顯的東西。 – miroxlav
如果您不想處理空值,請使用'Convert.ToString(rb)'。 –