What is meant by connection.Dispose() in C#?

后端 未结 4 2140
粉色の甜心
粉色の甜心 2021-01-12 10:09

What is meant by connection.Dispose() in C#?

4条回答
  •  南方客
    南方客 (楼主)
    2021-01-12 10:32

    A class implements IDisposable interface contains a method called Dispose(), where you can release resources or do something else.

    Also, a using statement can help to call Dispose() method automatically.

    using (SqlConnection connection  = new SqlConnection(connStr))
    {
       //do something
    }// it will automatically Dispose() here
    

    What happens when you call myClass.Dispose() depends on what you wrote in the Dispose method. For example:

    public class MyClass : IDisposable
    {
       //since MyClass implements IDisposable, it must contain a Dispose() method otherwise will compile error
       public void Dispose()
       {
          // do something
       }
    }
    

    so if you want to know what happened when you call connection.Dispose(), you must take a look at the Dispose() method of the class of connection(maybe it's a SqlConnection?). If it's a .NET built-in library(which means you can't get the source code easily), you can use a tool to help called Reflector

提交回复
热议问题