gpt4 book ai didi

.net - 如何覆盖类中属性的 .ToString

转载 作者:行者123 更新时间:2023-12-05 02:20:42 25 4
gpt4 key购买 nike

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

假设我有一个类:

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

我想覆盖属性 NumsDrawn 的 .ToString。

如果我将 .ToString 覆盖放在类中,那么它当然会覆盖类的 .ToString。我可以用它来输出列表中的所有数字,但我想更改抽奖中一个数字的输出。

Dim MyDraw = New ND(6)

MsgBox(MyDraw.ToString)

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

MsgBox(MyDraw.NumsDrawn(1).ToString)

谢谢!

最佳答案

我不确定您为什么要对 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

关于.net - 如何覆盖类中属性的 .ToString,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38196973/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com