by Jim
Nov 13, 2007 4:24 PM
I'm reorganizing my website and getting rid of the page with miscellaneous code. But I would hate for that code to go to the great recycle bin in the sky. That's what blogs are for, right?
So here's the first bit of code, a base class called WritableObject, in VB.NET. It uses reflection to write its members out in ToString(). I've found this useful when debugging stuff and wanting to "watch the data go by," as it were.
Imports System.Text
Imports System.Reflection
Public Class WritableObject
'This is an object that is capable of listing the names
'and values of its fields and properties. Derive from
'this class, but don't override the tostring() function;
'the ToString() here will output all the public properties
'and fields of the derived object.
Public Overrides Function toString() As String
Dim mi() As MemberInfo
Dim item As MemberInfo
Dim length As Integer
Dim obj As Object
Dim b As StringBuilder = New StringBuilder
b.Capacity = 5000
Try
'Write out the type of object I am
b.Append(Me.GetType.ToString())
b.Append(vbCrLf)
'And write out the fields
mi = Me.GetType.FindMembers( _
MemberTypes.Field, _
BindingFlags.Public Or BindingFlags.Instance, _
Nothing, _
Nothing)
'Look for the longest name, so I can line up the items/properties
length = 0
For Each item In mi
If item.Name.Length > length Then length = item.Name.Length
Next
For Each item In mi
b.Append(item.Name)
b.Append(New String(" ", length - item.Name.Length))
b.Append(": ")
If CType(item, FieldInfo).FieldType.Name = "ArrayList" Then
Dim list As ArrayList
list = Me.GetType.InvokeMember( _
item.Name, BindingFlags.GetField, Nothing, Me, Nothing)
If Not list Is Nothing Then
For Each o As Object In list
b.Append(vbCrLf)
b.Append(o.ToString())
Next
End If
Else
'If item.FieldType.fullName Then
obj = Me.GetType.InvokeMember( _
item.Name, BindingFlags.GetField, Nothing, Me, Nothing)
If Not obj Is Nothing Then b.Append(obj.ToString())
End If
b.Append(vbCrLf)
Next
Catch ex As Exception
b.Append("Error writing to string: " + ex.Message)
End Try
'Return the constructed string
Return b.ToString()
End Function
End Class