Dispose on nested Disposable items?

后端 未结 3 459
礼貌的吻别
礼貌的吻别 2021-01-18 21:21

I wanted to know if there are any conventions regarding disposal of disposable items nested inside another disposable item(in a property/public field, not as private members

3条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-18 22:12

    I would say that usually a container will dispose any contained disposable items - StreamReader disposes of the underlying stream, for example - but typically I will dispose of each item with a separate using statement anyway.

    Any concept of "ownership" is really just in documentation and convention. Basically you have to know what will dispose of what, which typically means reading the documentation and hoping it makes it clear. Unfortunately it doesn't always do so :(

    Note that there's no single correct answer here - sometimes you may want a type to behave one way, and sometimes the other. Some types explicitly allow you to state whether you're effectively transferring ownership of the resource, although most don't.

提交回复
热议问题