mardi 9 février 2016

Merging two objects in new instance and redirect references in C#

What I want to do is following:

  1. Create instance A of Type T1 (e.g. from a serialized xml file)
  2. Create instance B of Type T1 (or any derivation of it) (e.g. from a constructor of T1)
  3. Create instance C of Type T1 and merge properties and fields of A and B into it
  4. Look for objects referencing A or B and redirect this references to C

The Code should do following:

public class Foo
{
    public int Value { get; set; }
    public StrategyClass Strategy { get; set; }
}

public class StrategyClass
{
    public Foo ParentClass { get; set; }

    public int ReturnReferencedValue()
    {
        return ParentClass.Value;
    }
}          

And the merging should work like this:

int valueA = 1;
var strategy = new StrategyClass();
var A = new ReferenceTestClass() {Value = valueA };
var B = new ReferenceTestClass() {Strategy = strategy};
B.Strategy.ParentClass = B;

// Value and Strategy are copied. But Strategy is copied with its reference to B
ReferenceTestClass C = Merger.Merge(A, B);

// Here the copied strategy of B is called in C and should referece C
// Then this would return the copied Value of A located in C
Assert.AreEqual(valueA, C.Strategy.ReturnReferencedValue()) // Error because Strategy will return Value of B

I already achieved the Merger to copy all fields and properties. What is missing is the reference tracking and reference redirection.

I only found some diagnostic tool suggestions so far: Find references to the object in runtime

Thanks a lot.





Aucun commentaire:

Enregistrer un commentaire