Csharp/CSharp Tutorial/Statement/using — различия между версиями
Admin (обсуждение | вклад) м (1 версия) |
|
(нет различий)
|
Текущая версия на 12:20, 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
}
- obj is an object that is being used inside the using block.
- In the first form, the object is declared outside the using statement.
- In the second form, the object is declared within the using statement.
- When the block concludes, the Dispose() method (defined by the System.IDisposable interface) will be called on obj.
- The using statement applies only to objects that implement the System.IDisposable interface.