C#: Create strong reference between objects, without one referencing the other

后端 未结 4 1235
时光取名叫无心
时光取名叫无心 2021-02-13 23:55

Suppose I have 2 classes, Foo and Bar. Foo does not have (and cannot have) a relation to Bar.

However, I want a bar instance to stay alive, as long as it\'s foo instance

4条回答
  •  不要未来只要你来
    2021-02-14 00:17

    Have a look at the ConditionalWeakTable Class.

    Enables compilers to dynamically attach object fields to managed objects.

    It's essentially a dictionary where both the key and the value are a WeakReference, and the value is kept alive as long as the key is alive.

    For example, you can define a

    ConditionalWeakTable table
    

    and add a Foo/Bar pair. The Bar instance is kept alive as long as a reference to the Foo instance exists. You can find the Bar instance for the Foo instance by looking at the table.

提交回复
热议问题