如何使 CStr() 在盒装自定义数据类型上工作?

How to make CStr() working on boxed custom data type?

我可以在盒装内置 类型上成功使用 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

您可以这样覆盖 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<<

最好的方法是覆盖用户类型中的 .ToString。我相信 Cstr()CBool() 以及更多仍然存在以实现向后兼容性。 (VB6)

在你的类型中重写 .ToString 的另一个好处是,在调试时,当你观察你的类型的引用变量时,你会得到比对象类型更有意义的对象信息。