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

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

提交回复
热议问题