Overview
Defines a range that will release one or more objects outside this range
As an alias (namespace)
Treated as try-finally
Three different ways
Using directives
Using + namespace name, so that you can directly use the type in the command space in the program, without specifying a type of verbose namespace, similar to Java import, this function is the most common, almost every CS program will be used.
Example: Using System; Usually appear in the *.cs.
Using aliases
Using + aliases = Specific types that include detailed namespace information.
One advantage of this approach is that when the same CS references two different namespaces, but two namespaces include a type of the same name. When this type is needed, it is necessary to distinguish the types of the same names in each place using the detailed namespace method. The alias method will be more concise, which class will be used to give the class alias declaration. Note: Not that two names are duplicated, one is aliased, the other does not need to be aliased, and if two are to be used, two of them need to use a using to define the alias.
Using system;using AClass = namespace1.myclass;using Bclass = Namespace2.myclass; Namespace NameSpace1 {public class MyClass {public override string ToString () {return "You were in Namespace1.myclass"; }}} namespace NameSpace2 {class MyClass {public override string ToString () {return "You were in Namespace2.myclass"; }}} namespace testusing{using NameSpace1; Using NameSpace2; <summary>///CLASS1 Summary description. </summary> class Class1 {///<summary>//The main entry point of the application. </summary> [STAThread] static void Main (string[] args) {/////TODO: Add code here to launch the application//AClass my1 = new AClass (); Console.WriteLine (MY1); Bclass my2 = new Bclass (); Console.WriteLine (MY2); Console.WriteLine ("Press any Key"); Console.read (); } }}
Using defines a range
Common try-catch-finally:
SqlConnection myconnection = null; Example using clause: using (myconnection = new SqlConnection (connstring)) { myconnection.open (); } //Example Try/catch block: Try { myconnection = new SqlConnection (connstring); Myconnection.open (); } finally { myconnection.dispose (); }
Using implementation:
public void ExecuteCommand (string connstring, string commandstring) { using (SqlConnection myconnection = new SqlConnection (connstring)) { using (SqlCommand mysqlcommand = new SqlCommand ( CommandString, MyConnection)) { myconnection.open (); Mysqlcommand.executenonquery ();}}}
Summarize
Sometimes when you use the try/finally block, you will find that if an error occurs, the program will not make a mistake. I feel it is better to use the using statement.
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Using a little bit of understanding