【问题标题】:C# - Merge two objects of the same class and update all references?C# - 合并同一类的两个对象并更新所有引用?
【发布时间】:2011-07-29 16:25:50
【问题描述】:

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

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

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

有时我想合并属于不同 Bars 的 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&lt;Foo&gt;,它是从多个来源收集的。

如何让Baz 对象知道它们的Foos 何时过时? Foo 对象是否应该引用其“较新的”Foo 链表样式?还是有更好的办法?

【问题讨论】:

  • 您能说明Baz 对象如何从Bar 获取Foo 引用吗?谁负责设置Baz.Foos

标签: c# .net merge


【解决方案1】:

一大早我只能想到两种方法:

  • 不要总是分发参考资料 使用属性返回当前 参考
  • 实现 OnFooChange 事件并将更改发布给所有人 对 Bar 类/实例感兴趣的各方

马里奥

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-11-01
    • 2016-05-01
    • 2016-03-08
    • 1970-01-01
    • 1970-01-01
    • 2021-01-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多