1. using command. Using + namespace name, so that you can directly use the type in the Command Space in the program, without specifying the type of detailed namespace, similar to the Java import, this function is also the most commonly used, almost every cs program is used.
For example, using System; usually appears in *. cs.
2. using alias. Using + alias = contains the specific type of detailed namespace information.
This method has the advantage that when the same cs references two different namespaces, but both namespaces contain the same name type. When this type is required, the detailed namespace method should be used in every place to distinguish the types with the same name. The alias method is more concise. You can declare the alias for the class you use. Note: This does not mean that the two names are repeated. If you use an alias for one of them, you do not need to use the alias for the other. If you want to use both of them, you need to use using to define the alias for both of them.
For example:
Copy codeThe Code is as follows:
Using System;
Using aClass = NameSpace1.MyClass;
Using bClass = NameSpace2.MyClass;
Namespace NameSpace1
{
Public class MyClass
{
Public override string ToString ()
{
Return "You are in NameSpace1.MyClass ";
}
}
}
Namespace NameSpace2
{
Class MyClass
{
Public override string ToString ()
{
Return "You are in NameSpace2.MyClass ";
}
}
}
Namespace testUsing
{
Using NameSpace1;
Using NameSpace2;
/// <Summary>
/// Summary of Class1.
/// </Summary>
Class Class1
{
/// <Summary>
/// Main entry point of the application.
/// </Summary>
[STAThread]
Static void Main (string [] args)
{
//
// TODO: Add code here to start the application
//
AClass my1 = new aClass ();
Console. WriteLine (my1 );
BClass my2 = new bClass ();
Console. WriteLine (my2 );
Console. WriteLine ("Press any key ");
Console. Read ();
}
}
}
3. The using statement defines a range to process objects at the end of the range.
Scenario:
When a class instance is used in a code segment, you want to automatically call the Dispose of the class instance as long as you leave the code segment for whatever reason.
To achieve this goal, it is also possible to catch exceptions using try... catch, but it is also convenient to use using.
For example:
Copy codeThe Code is as follows:
Using (Class1 cls1 = new Class1 (), cls2 = new Class1 ())
{
// The code using cls1, cls2
} // Call the Dispose on cls1 and cls2
Here, the Dispose condition that triggers cls1 and cls2 is to reach the end of the using statement or throw an exception in the middle and control to exit the statement block.