我可以在盒装内置vb.net类型上成功使用CStr()
。但是如何用盒装自定义类型实现同样的目标呢?我得到了
Exception thrown: 'System.InvalidCastException' in Microsoft.VisualBasic.dll
代码:
' 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
答案 0 :(得分:1)
您可以这样覆盖ToString
:
Public Overrides Function ToString() As String
'Put the logic here
Return ">>" & Value.ToString() & "<<"
End
然后使用Convert.ToString()
方法将对象转换为字符串。
示例:
Dim r As New Record With {.Value = 3}
Dim rb As Object = r ' boxed into Object
MessageBox.Show("rb:" & Convert.ToString(rb)) 'Shows >>3<<
答案 1 :(得分:0)
最好的方法是覆盖用户类型中的.ToString
。我相信Cstr()
,CBool()
还有更多,以便向后兼容。 (VB6)
在类型中覆盖.ToString
的另一个好处是,在调试中,当您查看类型的引用变量时,您拥有的对象信息比对象类型更有意义。