Implementing IDisposable C#

前端 未结 1 629
谎友^
谎友^ 2021-01-27 11:20

I\'m having a little trouble understanding the IDisposable interface

I\'m developing a Game Engine and have ran code analysis on my solution and been told to implement t

相关标签:
1条回答
  • 2021-01-27 11:34

    You're on the right track. Anytime you have a class level variable that is disposable the containing class should also be disposable. And you're handling it properly from what I can tell. I don't see class name line so I can't tell if you have the IDisposable interface included but I imagine you do since you have implemented the methods. If not make sure you add it.
    IDisposable is a chain reaction type of implementation. If the variable is disposable, and it's only local to a method call then you dispose of it at the end of the call, but if it's at the class level you implement IDisposable and dispose of it with your class as you're doing. That way anyone using your class can dispose of it properly.

    So for example: Say I have a file open in my class...

    public class MyClass
    {
         private File txtFile = File.Create(...)
    }
    

    Now someone uses my class.

    private void useClass()
    {
         var myClass = new MyClass();
    }
    

    Well, they have just opened a file and it wasn't disposed of properly.

    Modify the code and it can be used like so...

    public sealed class MyClass : IDisposable
    {
         private File txtFile = new File.Create(...)
    
         public void Dispose()
         {
              txtFile.Dispose();
              GC.SuppressFinalize(this);
         }
    
         ~MyClass() => Dispose();
    }
    

    And when the use it they can use it like so...

    private void useClass()
    {
         using (var myClass = new MyClass())
         {
             //some code
         }
    }
    

    Hopefully this answers your questions. Just remember, is you declare a disposable object local to a method then you don't have to implement IDisposable in your class because you're going to dispose of it in that method. But if you implement it at class level scope, whether you have a method disposing it or not, you should implement IDisposable and check to make sure it's disposed when that containing class calls dispose. Make sense? Hope this helps.

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