Ridefinire il metodo ToString in VB.NET
Continuiamo il nostro studio del VB.NET con la ridefinizione del metodo ToString.
Come si legge dalla documentazione ufficiale, il metodo ToString di Object "Restituisce una stringa che rappresenta l'oggetto corrente".
Se ne abbiamo la necessità, possiamo ridefinirlo per i nostri oggetti custom, in modo da visualizzare quello che ci serve.
Ad esempio:
Public Class Book
Private title As String
Private author As String
Public Sub New(title As String, author As String)
Me.title = title
Me.author = author
End Sub
Public Overrides Function ToString() As String
Return String.Format("[{0} => {1}]", title, author)
End Function
End Class
Poi:
Module Module1
Sub Main()
Dim book = New Book("IT", "Stephen King")
Console.WriteLine(book.ToString)
End Sub
End Module
In console vedremo questo:
[IT => Stephen King]
Premere un tasto per continuare . . .
Enjoy!
vbnet tostring
Commentami!