.net 2.0新手学习笔记
CSDN给出的using 语句(C# 参考)
定义一个范围,将在此范围之外释放一个或多个对象。
using (Font font1 = new Font("Arial", 10.0f))
{
}
{
}
可以在 using 语句中声明对象(如上所示),或者在 using 语句之前声明对象,如下所示:
Font font2 = new Font("Arial", 10.0f);
using (font2)
{
// use font2
}
using (font2)
{
// use font2
}
可以有多个对象与 using 语句一起使用,但是必须在 using 语句内部声明这些对象,如下所示:
using (Font font3 = new Font("Arial", 10.0f),
font4 = new Font("Arial", 10.0f))
{
// Use font3 and font4.
}
font4 = new Font("Arial", 10.0f))
{
// Use font3 and font4.
}
下面的示例显示用户定义类可以如何实现它自己的 Dispose 行为。注意类型必须从 IDisposable 继承。
using System;
class C : IDisposable
{
public void UseLimitedResource()
{
Console.WriteLine("Using limited resource");
}
void IDisposable.Dispose()
{
Console.WriteLine("Disposing limited resource.");
}
}
class Program
{
static void Main()
{
using (C c = new C())
{
c.UseLimitedResource();
}
Console.WriteLine("Now outside using statement.");
Console.ReadLine();
}
}
class C : IDisposable
{
public void UseLimitedResource()
{
Console.WriteLine("Using limited resource");
}
void IDisposable.Dispose()
{
Console.WriteLine("Disposing limited resource.");
}
}
class Program
{
static void Main()
{
using (C c = new C())
{
c.UseLimitedResource();
}
Console.WriteLine("Now outside using statement.");
Console.ReadLine();
}
}