.Net开发中的@ 和 using 使用技巧

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了.Net开发中的@ 和 using 使用技巧相关的知识,希望对你有一定的参考价值。

一、@符号的妙用

1、可以作为保留关键字的标识符

C#规范当中,不允许使用保留关键字(class、bool等)当作普通的标识符来命名,这时候@符号作用就体现

出来了,可以通过@符号前缀把这些保留关键字可以当作普通的字符使用。

比如:

string @class="hello";  //是正确的

string class="hello";   //报错

2、@符号可以表示跨行字符串

比如:

string [email protected]"hello

             world

 !"; //这样写是正确的

 

3、字符串转义字符

很多时候程序中出现目录的时候会有“\\”,字符表示转义字符,要表示普通字符的时候需要写成“\\\\”,当这样字符过多的时候写起来不是很简洁,这时候可以使用@字符。

比如:

string path="d:\\\\Data\\\\web\\\\ss.txt";//一般写法

string [email protected]"d:\\Data\\web\\ss.txt";//使用@符号

 

二、using的用法

1、using 指令

用来引入命名空间,比如:using System;

2、为命名空间或类型创建别名

 using引入命名空间,并不等于编译器编译时加载该命名空间所在的程序集,程序集的加载决定于程序中对该程序集是否存在调用操作,

 如果代码中不存在任何调用操作则编译器将不会加载using引入命名空间所在程序集。

 创建别名的另一个重要的原因在于同一文件中引入的不同命名空间中包括了相同名称的类型,

 例如SharpMap.Geometries.Point与System.Drawing.Point。为了避免出现名称冲突,可以通过设定别名来解决:

 using SGPoint = SharpMap.Geometries.Point;

 using SDPoint = System.Drawing.Point;

 

 尽管我们可以通过类型全名称来加以区分,但是这显然不是最佳的解决方案。用using指令创建别名,

 有效的解决了这种可能的命名冲突,才是最佳的解决方案。

 3、using语句

 using 语句允许程序员指定使用资源的对象应当何时释放资源。using 语句中使用的对象必须实现 IDisposable 接口。

 IDisposable接口提供了 Dispose 方法,该方法将释放此对象的资源。

 例如:

 

技术分享
 using(TextReader reader=new StreamReader(filename))

{

  string line;

  whil((line=read.ReadLine())!=null)

  {

     Console.WriteLine(line);

  }

}
技术分享

 

 

等价于以下形式:

技术分享
{

 TextReader reader=new StreamReader(filename);

 try

 {

  string line;

  while((line=read.ReadLine())!=null)

   {

     Console.WriteLine(line);

   }

 }

 finally

  {

    if(reader!=null)

    {

       (IDisposible)reader.Dispose();

    }

   }

}
技术分享
 
 
以上文章 转载自  http://www.cnblogs.com/hgmyz/p/6991034.html

以上是关于.Net开发中的@ 和 using 使用技巧的主要内容,如果未能解决你的问题,请参考以下文章

error: ‘_beginthreadex‘ undeclared (first use in this function); did you mean ‘SDL_beginthread‘?(代码片

Flink producer attempted to use a producer id which is not currently assigned to its transaction(代码片

Android studio提示Android Gradle plugin requires Java 11 to run. You are currently using Java 1.8.(代码片

Android studio提示Android Gradle plugin requires Java 11 to run. You are currently using Java 1.8.(代码片

.Net开发小技巧

在 Unity 5 中使用 .NET 4.5 代码