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

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

提交回复
热议问题