如何重载 BasicType.ToString()

How to overload BasicType.ToString()

我想为 Integer 重载 ToString() 方法,但仅在某个 class 内(即当我在 Foo 内调用 Integer.ToString 时class 它使用我的重载,当我在 Foo 之外调用它时 class 它使用标准方法)

首先,这可能吗?

其次,我想要重载它的原因是我可以让它用一些漂亮的格式制作一个整数的每个字节的十六进制值的字符串,例如如果我的整数是 &HA55A 那么 MyInteger.ToString 将 return 一个字符串 = "5A A5" (Little-endian)。超载是要走的路吗?或者覆盖,或者扩展?

第三,我尝试过如下重载,但同一个 class 中的调用似乎仍然使用正常的 ToString(),这意味着它会导致“42330”。

Public Class Foo
    Public Sub Bar ()
        Dim MyInt As Integer = 42330
        Dim BetterString As New String(MyInt.ToString) ' Should use the ToString() below 
        'to give "5A A5" not "42330"
    End Sub

    Public Overloads Function ToString(i As Integer) As String
        Dim a As Byte() = BitConverter.GetBytes(i)
        Dim RetVal As New System.Text.StringBuilder(a.Length * 3)
        Dim ByteStr As String
        Dim Last As Integer = a.Length - 1

        For Index As Integer = 0 To Last
            ByteStr = New String(Conversion.Hex(a(Index)))
            If ByteStr.Length = 1 Then
                RetVal.Append("0")
            End If
            RetVal.Append(ByteStr)
            If i <> Last Then
                RetVal.Append(" ")
            End If
        Next
        Return RetVal.ToString
    End Function
End Class

Public Class Wiz
    Public Sub Pop
        Dim MyInt As Integer = 42330
        Dim MyString As NewString(MyInt.ToString) ' Should always be "42330"
    End Sub
End Class

我几乎是 VB.Net 的新手,所以我仍在努力寻找实现我想要的目标的最佳方法。

我会添加一个扩展方法。类似于:

Module IntegerExtensions
    <Extension()> 
    Public Function ToHex(ByVal i As Integer) As String
        Return Microsoft.VisualBasic.Conversion.Hex( i )
    End Function 
End Module

然后在任何需要十六进制值的地方调用 ToHex。

您不能真正将 ToString 更改为 Integer,即使可以,也不是一个好主意 - 这会造成混淆。最好有两个单独的方法,在需要十六进制字符串时使用 ToHex,在需要常规字符串时使用 ToString。它还使代码更具可读性。当您看到 ToHex 或 ToHexadecimalString 或 ToHexString 时,您就会知道代码在做什么。即使当有人看到 ToString 时你确实让它工作了,他们也不会很明显地知道他们会得到一个十六进制字符串。