Disposing members of an instance of an unknown type
This is for a program that has a built-in script system (using CodeDom), and requires the objects that were created by the script to be disposed before updating/re-compiling the script, in order to stop the execution of the older assembly.
I'm trying to make a generic method to dispose an instance of any class, so that scripters don't need to implement IDisposable.
Let's say the scripter created a class, with unknown contents, that may not implement IDisposable.
Like this:
vb Code:
Public Class foo
Dim obj1 As New managedType1()
Dim obj2 As New managedType2()
Dim var1 As unmanagedType1
End Class
How to dispose myFoo?
I've tried it this way (with a class that has StructLayout attribute):
vb Code:
Public Shared Sub DisposeObj(ByVal obj As Object)
If TypeOf obj Is IDisposable Then
CType(obj, IDisposable).Dispose()
Exit Sub
End If
Dim typeOfObj As Type = obj.GetType()
If typeOfObj.StructLayoutAttribute Is Nothing Then Exit Sub
Dim gch As GCHandle = GCHandle.Alloc(obj)
Dim offset As Integer
Dim memberObj As Object
'try to dispose the members of this class
For Each member As Reflection.MemberInfo In typeOfObj.GetMembers(Reflection.BindingFlags.NonPublic Or Reflection.BindingFlags.Instance Or Reflection.BindingFlags.DeclaredOnly)
offset = Marshal.OffsetOf(typeOfObj, member.Name).ToInt32
memberObj = GCHandle.FromIntPtr(New IntPtr(GCHandle.ToIntPtr(gch).ToInt32 + offset)).Target
DisposeObj(memberObj)
Next
End Sub
But line 17 returns obj. I know this wasn't even supposed to work, because the offset doesn't tell where the member instance is allocated.
Any other ideas?