如何覆盖类

时间:2016-07-05 06:53:01

标签: .net vb.net properties tostring overrides

我首先搜索了这个,并且有一些类似的帖子,但我无法找到答案。 :(

假设我有一个班级:

Public Class ND
    Private mNumsDrawn = New List(Of Integer)

    Public Sub New(ByVal vNum As Integer)
        For i = 1 To vNum
            mNumsDrawn.Add(0)
        Next
    End Sub

    Public Property NumsDrawn As List(Of Integer)
        Get
            Return mNumsDrawn
        End Get
        Set(ByVal value As List(Of Integer))
            mNumsDrawn = value
        End Set
    End Property
End Class

我想覆盖Property NumsDrawn的.ToString。

如果我把.ToString覆盖在类中,那么它只是覆盖了类' .ToString当然。我可以使用它来输出列表中的所有数字,但我想在绘图中更改一个数字的输出。

Dim MyDraw = New ND(6)

MsgBox(MyDraw.ToString)

但我想要的是这样......

MsgBox(MyDraw.NumsDrawn(1).ToString)

谢谢!

2 个答案:

答案 0 :(得分:2)

您要求的是覆盖ToString()的{​​{1}}方法。虽然这是可能的,但IMO并没有真正有用。

更有用的是在ND上定义扩展方法。请注意,扩展方法需要放在ND(实际上是静态类)中。

这可以按如下方式完成:

Public Module

如果您仍想覆盖 <Extension> Public Function ToFormattedValue(instance As ND, index As Integer) As String Return instance.NumsDrawn(index).ToString() End Function ' Use as: MessageBox.Show(MyDraw.ToFormattedValue(1)) 方法,则代码几乎相同。它并没有真正压倒它只是添加一个过载。像这样:

ToString

答案 1 :(得分:1)

我不确定您为什么要在Integer类型上进行自定义.ToString()覆盖...但是......

执行此操作的一种简单方法是将NumsDrawnList(Of Integer)更改为List(Of NumClass),然后覆盖上的.ToString 上课:

Public Class ND
    Private mNumsDrawn As List(Of NumClass) = New List(Of NumClass)

    Public Sub New(ByVal vNum As Integer)
        For i = 1 To vNum
            mNumsDrawn.Add(New NumClass(0))
        Next
    End Sub

    Public Property NumsDrawn As List(Of NumClass)
        Get
            Return mNumsDrawn
        End Get
        Set(ByVal value As List(Of NumClass))
            mNumsDrawn = value
        End Set
    End Property
End Class

Public Class NumClass
    Public Property Value As Integer
    Public Sub New(value As Integer)
        Me.Value = value
    End Sub
    Public Overrides Function ToString() As String
        Return "Here is my formatted value: " & Me.Value
    End Function
End Class

用法:

    Dim myND As New ND(99)
    Debug.WriteLine(myND.NumsDrawn(6).ToString()) 'outputs:- Here is my formatted value: 0