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

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

Версия 15:31, 26 мая 2010

Demonstrate a using alias

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(); 
  } 
}

Demonstrate the using directive

using System; 
 
using Counter; 
 
namespace Counter { 
  class MyClass { 
  } 
} 
 
class MainClass { 
  public static void Main() { 
    MyClass cd1 = new MyClass(); 
  } 
}

IDisposable and the using Keyword

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())
        {
        }
    }
}

using

There are two forms of the using directive.

The first form:


using nameOfANameSpace;

using alias directive

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

using Statement

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

It has these general forms:


using (obj) {
    // use obj 
    }
    
    using (type obj = initializer) {
    // use obj 
    }
  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.