zoukankan      html  css  js  c++  java
  • C# using用法

    一、using指令

      使用using指令在文件顶部引入命名空间,如

    using System;
    using System.IO;
    

      

    二、using别名

      用using为命名空间或类型定义别名,当引入的多个命名空间包含相同名字的类型时,需要使用该类型时,可以通过using为其指定别名,使代码更加简洁,避免冲突,例如:

    using System;
    using aTest = nameSpaceA.Test;
    using bTest = nameSpaceB.Test;
    
    namespace @using
    {
        class Program
        {
            static void Main(string[] args)
            {
                aTest a = new aTest();  //aTest 代替 nameSpaceA.Test
                a.fun();
                bTest b = new bTest(); //bTest 代替 nameSpaceB.Test
                b.fun();
                Console.ReadKey();
            }
        }
    }
    
    namespace nameSpaceA
    {
        public class Test
        {
            public void fun()
            {
                Console.WriteLine("this is test a");
            }
        }
    
    }
    
    namespace nameSpaceB
    {
        public class Test
        {
            public void fun()
            {
                Console.WriteLine("this is test b");
            }
        }
    
    }
    

      输出:this is test a

         this is test b

    三、using语句

      某些类型的非托管对象有数量限制或很耗费系统资源,在代码使用完它们后,尽可能快的释放它们时非常重要的。using语句有助于简化该过程并确保这些资源被适当的处置(dispose)。

    它有两种使用形式。

    1:

     using (ResourceType Identifier = Expression ) Statement

     圆括号中的代码分配资源,Statement是使用资源的代码

     using语句会隐式产生处置该资源的代码,其步骤为:

     a:分配资源

     b:把Statement放进tyr块

     c:创建资源的Dispose方法的调用,并把它放进finally块,例如:

    using System;
    using System.IO;
    
    namespace @using
    {
        class Program
        {
            static void Main(string[] args)
            {
                using (TextWriter tw = File.CreateText("test.txt"))
                {
                    tw.Write("this is a test");
                }
               
                using (TextReader tr = File.OpenText("test.txt"))
                {
                    string input;
                    while ((input = tr.ReadLine()) != null)
                    {
                        Console.WriteLine(input);
                    }
                }
                Console.ReadKey();
            }
        }
    }

    输出:this is a test

    2:

    using (Expression)  Statement

    Expression 表示资源,Statement是使用资源,资源需要在using之前声明

    TextWriter tw = File.CreateText("test.txt");
    using(tw){......}

    这种方式虽然可以确保对资源使用结束后调用Dispose方法,但不能防止在using语句已经释放了他的非托管资源之后使用该资源,可能导致不一致的状态,不推荐使用

      

  • 相关阅读:
    如何在eclipse开发环境中连接数据库?oracle和db2
    oracle数据库表的记录误删后如何恢复
    人事经理眼中的好简历
    JavaScript常用方法
    如何解决plsql被用户锁定的问题?
    eclipse 快捷键
    刚开始用9.3的版本,一堆问题。(转)
    十条不错的编程观点(转)
    http://localhost:8099无法登录,出现incorrect info报错信息,怎么办?
    http://localhost:8399/arcgis/rest/services 无法访问,怎么办?
  • 原文地址:https://www.cnblogs.com/forever-Ys/p/10291508.html
Copyright © 2011-2022 走看看