Summary of several USES of using

  • 2020-05-26 08:19:29
  • OfStack

1. using instructions. The using + namespace name, which allows you to use the type in the command space directly in your program without specifying a specific namespace for the type, is similar to Java's import, which is also the most common, and is used by almost every cs program.
For example: using System; 1 generally appears in *.cs.

2. using alias. using + alias = the specific type that includes detailed namespace information.
One advantage of this approach is when the same cs references two different namespaces, but both namespaces include a type with the same name. When this type is needed, use a detailed namespace method to distinguish the types with the same name everywhere. The alias method is more concise, and you can just declare the alias to the class you use. Note: this does not mean that two names are repeated. If one name is aliased, the other name will not need to be aliased. If both names are used, both names will need to be aliased using using.

Such as:


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>
    /// Class1  A summary of. 
    /// </summary>
    class Class1
    {
        /// <summary>
        ///  The application's main entry point. 
        /// </summary>
        [STAThread]
        static void Main(string[] args)
        {
            //
            // TODO:  Add the 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.using statement, which defines a scope and processes the object at the end of the scope.
Scene:
When an instance of a class is used in a code snippet, it is expected that Dispose of the class instance will be automatically called whenever it leaves the code snippet for whatever reason.
To do this, use try... It is also possible to catch exceptions with catch, but it is also convenient to use using.
Such as:


using (Class1 cls1 = new Class1(), cls2 = new Class1())
{
  // the code using cls1, cls2

} // call the Dispose on cls1 and cls2

The Dispose condition that triggers cls1 and cls2 is that an exception is raised at the end of the using statement or in the middle of the statement and the control leaves the statement block.


Related articles: