Question

(using vb.Net 4.0) Say you have an object whose graph is fairly complex - it has properties, arrays and other collections, subclasses with their own properties and collections, etc. I want to fully traverse the entire object graph and find all instances of a particular type T, to then perform a particular operation on these instances. Is there a bulletproof way to perform a full traversal of the object graph? Even with reflection, this seems a difficult task that is prone to error.

I was wondering about binary serialization, since that seems to clone an object, no matter how complicated, in a fairly robust manner. Is there any way to modify that technique, such that instead of serializing it instead returns a list of references to all sub-objects of given type T? But that is just pure speculation, I'm open to any feasible solution.

Was it helpful?

Solution

Well I figured out a method, though it probably isn't the best. Because my object's graph was pretty nested & complex, I decided to rely on binary serialization, since in my (limited) experience it offers the most thorough & robust graph traversal. The downside is binary serialization can impact performance significantly, but after benchmarking it doesn't appear to be the limiting factor for my particular situation.

Basically, I have my type T implement ISerializable, then I can handle the post-serialization by adding to the class:

 Protected Sub New(ByVal info As System.Runtime.Serialization.SerializationInfo,
                           ByVal context As System.Runtime.Serialization.StreamingContext)

Another way (without implementing Iserializable) is create a post-serialized method with the "OnDeserialized" attribute.

Anyways, you can put info into the streamingContext object, which I used to describe the operation I want performed on the Type T instances. So basically, serialize the parent object, which will find and serialize all sub-objects of type T, which can then be coded to perform any desired task upon deserialization. Going forward, you then deal only with the serialized objects.

Obviously, serialization can have complications, and this method won't work for all situations. Pretty inelegant performance-wise too. But I needed a hassle-free & thorough object graph traversal so there you go.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top