码迷,mamicode.com
首页 > Windows程序 > 详细

C# using用法

时间:2019-01-19 14:23:35      阅读:190      评论:0      收藏:0      [点我收藏+]

标签:sys   pen   writer   final   exp   his   null   fun   space   

一、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语句已经释放了他的非托管资源之后使用该资源,可能导致不一致的状态,不推荐使用

  

C# using用法

标签:sys   pen   writer   final   exp   his   null   fun   space   

原文地址:https://www.cnblogs.com/forever-Ys/p/10291508.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!