Use of Finalize/Dispose method in C#

后端 未结 13 2324
轮回少年
轮回少年 2020-11-21 23:20

C# 2008

I have been working on this for a while now, and I am still confused about the use of finalize and dispose methods in code. My questions are below:

13条回答
  •  谎友^
    谎友^ (楼主)
    2020-11-21 23:37

    nobody answered the question about whether you should implement IDisposable even though you dont need it.

    Short answer : No

    Long answer:

    This would allow a consumer of your class to use 'using'. The question I would ask is - why would they do it? Most devs will not use 'using' unless they know that they must - and how do they know. Either

    • its obviuos the them from experience (a socket class for example)
    • its documented
    • they are cautious and can see that the class implements IDisposable

    So by implementing IDisposable you are telling devs (at least some) that this class wraps up something that must be released. They will use 'using' - but there are other cases where using is not possible (the scope of object is not local); and they will have to start worrying about the lifetime of the objects in those other cases - I would worry for sure. But this is not necessary

    You implement Idisposable to enable them to use using, but they wont use using unless you tell them to.

    So dont do it

提交回复
热议问题