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

C# using的用法

时间:2016-11-02 20:07:30      阅读:294      评论:0      收藏:0      [点我收藏+]

标签:结束   rgs   encoding   finally   log   定义   space   classname   current   

1.在文件顶部引用命名空间,如:using System;

2.为命名空间或类型定义别名;

  如果命名空间过长,键入时会比较麻烦,如果该命名空间会在代码中多次调用的话,那么为命名空间定义别名,是比较明智的选择,并且还能够避免类名冲突!是不是很机智啊?!

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
//为命名空间定义别名 "ElseName"
using ElseName = This.Is.Very.Very.Long.NamespaceName;
//为类定义定义别名
using ElseCName = This.Is.Very.Very.Long.NamespaceName.ThisIsVeryVeryLongClassName;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        //通过别名实例化对象   ::是命名空间别名的修饰符
        ElseName::NamespaceExample NSEx = new ElseName::NamespaceExample();
        //通过别名实例化对象
        ElseCName CN = new ElseCName();
        Response.Write("命名空间:" + NSEx.GetNamespace() + ";类名:" + CN.GetClassName());
    }
}

namespace This.Is.Very.Very.Long.NamespaceName
{
    class NamespaceExample
    {
        public string GetNamespace()
        {
            return this.GetType().Namespace;
        }
    }

    class ThisIsVeryVeryLongClassName
    {
        public string GetClassName()
        {
            return System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.FullName;
        }
    }
}

 

3.使用using,定义范围,在该范围结束时回收资源。

  注意使用前提:该对象必须继承了IDisposable接口,功能等同于try{}catch{}Finally{}。

string str = "LittleBai";
//创建写入字符串
Byte[] bytesToWrite = Encoding.Default.GetBytes(str); ;
//创建文件
using (FileStream fs = new FileStream("test.txt", FileMode.Create))
{
    //将字符串写入文件
    fs.Write(bytesToWrite, 0, bytesToWrite.Length);
}

  执行完成后,程序会自动回收资源!

 

交流群:225443677  

C# using的用法

标签:结束   rgs   encoding   finally   log   定义   space   classname   current   

原文地址:http://www.cnblogs.com/LittleBai/p/6024022.html

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