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

后端 未结 29 2878
有刺的猬
有刺的猬 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:49

    I've used it a lot in the past to work with input and output streams. You can nest them nicely and it takes away a lot of the potential problems you usually run into (by automatically calling dispose). For example:

            using (FileStream fs = new FileStream("c:\file.txt", FileMode.Open))
            {
                using (BufferedStream bs = new BufferedStream(fs))
                {
                    using (System.IO.StreamReader sr = new StreamReader(bs))
                    {
                        string output = sr.ReadToEnd();
                    }
                }
            }
    
    0 讨论(0)
  • 2020-11-21 07:50

    You can make use of the alias namespace by way of the following example:

    using LegacyEntities = CompanyFoo.CoreLib.x86.VBComponents.CompanyObjects;
    

    This is called a using alias directive as as you can see, it can be used to hide long-winded references should you want to make it obvious in your code what you are referring to e.g.

    LegacyEntities.Account
    

    instead of

    CompanyFoo.CoreLib.x86.VBComponents.CompanyObjects.Account
    

    or simply

    Account   // It is not obvious this is a legacy entity
    
    0 讨论(0)
  • 2020-11-21 07:50

    using is used when you have a resource that you want disposed after it's been used.

    For instance if you allocate a File resource and only need to use it in one section of code for a little reading or writing, using is helpful for disposing of the File resource as soon as your done.

    The resource being used needs to implement IDisposable to work properly.

    Example:

    using (File file = new File (parameters))
    {
        *code to do stuff with the file*
    }
    
    0 讨论(0)
  • 2020-11-21 07:52

    Another great use of using is when instantiating a modal dialog.

    Using frm as new Form1
    
    Form1.ShowDialog
    
    ' do stuff here
    
    End Using
    
    0 讨论(0)
  • 2020-11-21 07:53

    The reason for the using statement is to ensure that the object is disposed as soon as it goes out of scope, and it doesn't require explicit code to ensure that this happens.

    As in Understanding the 'using' statement in C# (codeproject) and Using objects that implement IDisposable (microsoft), the C# compiler converts

    using (MyResource myRes = new MyResource())
    {
        myRes.DoSomething();
    }
    

    to

    { // Limits scope of myRes
        MyResource myRes= new MyResource();
        try
        {
            myRes.DoSomething();
        }
        finally
        {
            // Check for a null resource.
            if (myRes != null)
                // Call the object's Dispose method.
                ((IDisposable)myRes).Dispose();
        }
    }
    

    C# 8 introduces a new syntax, named "using declarations":

    A using declaration is a variable declaration preceded by the using keyword. It tells the compiler that the variable being declared should be disposed at the end of the enclosing scope.

    So the equivalent code of above would be:

    using var myRes = new MyResource();
    myRes.DoSomething();
    

    And when control leaves the containing scope (usually a method, but it can also be a code block), myRes will be disposed.

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

    Since a lot of people still do:

    using (System.IO.StreamReader r = new System.IO.StreamReader(""))
    using (System.IO.StreamReader r2 = new System.IO.StreamReader("")) {
       //code
    }
    

    I guess a lot of people still don't know that you can do:

    using (System.IO.StreamReader r = new System.IO.StreamReader(""), r2 = new System.IO.StreamReader("")) {
       //code
    }
    
    0 讨论(0)
提交回复
热议问题