开发者

C# - Merge two objects of the same class and update all references?

I have some Foo objects which are contained in Bar objects:

class Foo
{
    int uniqueId; // every Foo has a different ID.
    List<int> data;
}

class Bar
{
    Foo foo = new Foo();
}

Sometimes I want to merge the Foo objects that belong to different Bars as follows:

public void MergeWith(Bar otherBar)
{
    this.foo.uniqueId = otherbar.foo.uniqueId;
    this.foo.data.AddRange(otherbar.foo.data);     

    otherBar.foo = this.foo;
    // Now both Bar objects refer to the same Foo, which contains all the data.
}
Bar bar1;
Bar bar2;
bar1.MergeWith(bar2);

This is fine. The problem is that these Bar objects have handed out a references to their Foo objects to Baz objects. Baz has a List<Foo> it's collected from multiple sources.

How can I get the Baz objects to know when their Foos开发者_如何学Go are outdated? Should the Foo objects have a reference to their "newer" Foo, linked list style? Or is there a better way?


I can only think of two ways that early in the morning:

  • Do not hand out a reference always use a property to return the current reference
  • Implement a OnFooChange event and post the change to all parties interested from within the Bar class/ instance

hth

Mario

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜