What are the uses of “using” in C#?

后端 未结 29 2879
有刺的猬
有刺的猬 2020-11-21 07:31

User kokos answered the wonderful Hidden Features of C# question by mentioning the using keyword. Can you elaborate on that? What are the uses of

相关标签:
29条回答
  • 2020-11-21 07:55

    The using keyword defines the scope for the object and then disposes of the object when the scope is complete. For example.

    using (Font font2 = new Font("Arial", 10.0f))
    {
        // use font2
    }
    

    See here for the MSDN article on the C# using keyword.

    0 讨论(0)
  • 2020-11-21 07:55

    Thanks to the comments below, I will clean this post up a bit (I shouldn't have used the words 'garbage collection' at the time, apologies):
    When you use using, it will call the Dispose() method on the object at the end of the using's scope. So you can have quite a bit of great cleanup code in your Dispose() method.
    A bullet point here which will hopefully maybe get this un-markeddown: If you implement IDisposable, make sure you call GC.SuppressFinalize() in your Dispose() implementation, as otherwise automatic garbage collection will try to come along and Finalize it at some point, which at the least would be a waste of resources if you've already Dispose()d of it.

    0 讨论(0)
  • 2020-11-21 07:57

    Another example of a reasonable use in which the object is immediately disposed:

    using (IDataReader myReader = DataFunctions.ExecuteReader(CommandType.Text, sql.ToString(), dp.Parameters, myConnectionString)) 
    {
        while (myReader.Read()) 
        {
            MyObject theObject = new MyObject();
            theObject.PublicProperty = myReader.GetString(0);
            myCollection.Add(theObject);
        }
    }
    
    0 讨论(0)
  • Everything outside the curly brackets is disposed, so it is great to dispose your objects if you are not using them. This is so because if you have a SqlDataAdapter object and you are using it only once in the application life cycle and you are filling just one dataset and you don't need it anymore, you can use the code:

    using(SqlDataAdapter adapter_object = new SqlDataAdapter(sql_command_parameter))
    {
       // do stuff
    } // here adapter_object is disposed automatically
    
    0 讨论(0)
  • 2020-11-21 07:59

    Not that it is ultra important, but using can also be used to change resources on the fly. Yes disposable as mentioned earlier, but perhaps specifically you don't want the resources they mismatch with other resources during the rest of your execution. So you want to dispose of it so it doesn't interfere elsewhere.

    0 讨论(0)
  • 2020-11-21 08:00

    The Rhino Mocks Record-playback Syntax makes an interesting use of using.

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