簡體   English   中英

C#-合並同一類的兩個對象並更新所有引用?

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

我有一些包含在Bar對象中的Foo對象:

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

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

有時我想合並屬於不同Bar的Foo對象,如下所示:

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);

這可以。 問題在於這些Bar對象已經將對Foo對象的引用分發給Baz對象。 Baz有一個List<Foo>它是從多個來源收集的。

我怎樣才能知道Baz對象的Foo何時過時? Foo對象是否應該引用其“較新的” Foo鏈表樣式? 或者,還有更好的方法?

我只能想到凌晨的兩種方式:

  • 不要分發參考,始終使用屬性來返回當前參考
  • 實施OnFooChange事件,並將更改發布到Bar類/實例內的所有感興趣的各方

hth

馬里奧

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM