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

后端 未结 4 1169
时光取名叫无心
时光取名叫无心 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:10

    Can you create a public object field called BarReference in type Foo?
    Someone outside of Foo should set the proper instance of Bar to this property.
    As long as there is a reference to the bar instance it won't be GCed AND using object Foo doesn't know anything about Bar type.

    0 讨论(0)
  • 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<Foo, Bar> 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.

    0 讨论(0)
  • 2021-02-14 00:18

    Bar can only not be finalized if SOMETHING has a reference to it. Just have Foo tell that thing when it can let go of Bar.

    0 讨论(0)
  • 2021-02-14 00:22

    It's difficult to give suggestions without knowing exactly what you're trying to achieve, or what you mean by "alive". Normally you shouldn't need to worry about lifetime of managed objects: they "die" naturally when they're no longer referenced.

    But to do what you appear to want, either your Foo instance must reference the Bar instance, or some other object must reference both in order to create the link. It could be a reference to a Bar instance as a System.Object, i.e. Foo doesn't need to know about the Bar Type.

    0 讨论(0)
提交回复
热议问题