/*
using 用法
* using +namespace ,这样可以直接用namespace的所有类型,而不用指定命名空间的详细路径。
using System;
Console.WriteLine("using System; is to omit System. later");
* using +alias=namespace
using a=System;
* using is easy to dispose object
*/
using System;
using System.IO;
class Test
{
static void Main()
{
Console.WriteLine("Enter file path");
string fileSec = Console.ReadLine();
FileStream fs = new FileStream(fileSec, FileMode.OpenOrCreate);
using (A a = new A(fs))
{
a.DoSomething();
}
Console.ReadLine();
//A a = new A();
//try
//{
// DoSomething();
//}
//finally
//{
// if (a != null)
// {
// a.Dispose();
// }
//}
}
}
class A:IDisposable
{
private bool _dispose;
private Stream _stream;
public A(Stream stream)
{
if (stream == null)
{
throw new ArgumentNullException("ArgumentNullException");
}
if (!stream.CanRead)
{
throw new ArgumentException("the stream is not readable");
}
_stream = stream;
}
public void DoSomething()
{
//...
System.Console.Write("the stream length:"+_stream.Length);
}
#region IDisposable 成员 //implement interface
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
#endregion
public void Dispose(bool dispose)
{
if (!_dispose)
{
if (dispose)
{
if (_stream != null)
{ _stream.Dispose(); }
}
_stream = null;
}
}
}
回复 引用 查看