Csharp/CSharp Tutorial/Statement/using — различия между версиями

Материал из .Net Framework эксперт
Перейти к: навигация, поиск
м (1 версия)
 
(нет различий)

Текущая версия на 15:20, 26 мая 2010

Demonstrate a using alias

<source lang="csharp">using System;

// Create an alias for Counter.CountDown. using Count = Counter.MyClass;

namespace Counter {

 class MyClass { 
 } 

}

class MainClass {

 public static void Main() { 
   Count cd1 = new Count(); 
 } 

}</source>

Demonstrate the using directive

<source lang="csharp">using System;

using Counter;

namespace Counter {

 class MyClass { 
 } 

}

class MainClass {

 public static void Main() { 
   MyClass cd1 = new MyClass(); 
 } 

}</source>

IDisposable and the using Keyword

<source lang="csharp">using System;

public class MyClass : IDisposable {

   public MyClass()
   {
       Console.WriteLine("constructor");
   }
  
   ~MyClass()
   {
       Console.WriteLine("destructor");
   }
  
   public void Dispose()
   {
       Console.WriteLine("implementation of IDisposable.Dispose()");
   }

}

public class MainClass {

   static void Main()
   {
       using(MyClass MyObject = new MyClass())
       {
       }
   }

}</source>

using

There are two forms of the using directive.

The first form:


<source lang="csharp">using nameOfANameSpace;</source>

using alias directive

<source lang="csharp">using MyNameSpaceFormSystem = System; using MyNameSpaceFormSystemConsole = System.Console; class MainClass {

  static void Main()
  {
     MyNameSpaceFormSystem.Console.WriteLine("test");
     System.Console.WriteLine("test");
     MyNameSpaceFormSystemConsole.WriteLine("test");
  }

}</source>

test
test
test

using Statement

using has a second form that is called the using statement.

It has these general forms:


<source lang="csharp">using (obj) {

   // use obj 
   }
   
   using (type obj = initializer) {
   // use obj 
   }</source>
  1. obj is an object that is being used inside the using block.
  2. In the first form, the object is declared outside the using statement.
  3. In the second form, the object is declared within the using statement.
  4. When the block concludes, the Dispose() method (defined by the System.IDisposable interface) will be called on obj.
  5. The using statement applies only to objects that implement the System.IDisposable interface.