using-statement
using 陳述式是用來讓一實體在一個範圍內使用,
超出範圍外,實體就會自動解構。來看以下範例。
一、using statement
using System;
using System.IO;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
using (StreamReader sr = new StreamReader(@"mytext.txt"))
{
Console.WriteLine(sr.ReadToEnd());
}
Console.ReadKey();
}
}
}
二、在 C# 8.0,using statement 可寫成
using System;
using System.IO;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
{
using StreamReader sr = new StreamReader(@"mytext.txt");
Console.WriteLine(sr.ReadToEnd());
}
Console.ReadKey();
}
}
}
被添加 using 修飾詞的變數 sr,將存活在黃色範圍內,
超出其範圍,該變數將會被自動解構。
三、using statement 宣告多個實體
using System;
using System.IO;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
using (StreamReader sr = new StreamReader(@"mytext.txt"),
sr2 = new StreamReader(@"mytext.txt"))
{
Console.WriteLine(sr.ReadToEnd());
Console.WriteLine(sr2.ReadToEnd());
}
Console.ReadKey();
}
}
}
四、在 C# 8.0,using statement 宣告多個實體可寫成
using System;
using System.IO;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
using StreamReader sr = new StreamReader(@"mytext.txt"),
sr2 = new StreamReader(@"mytext.txt");
Console.WriteLine(sr.ReadToEnd());
Console.WriteLine(sr2.ReadToEnd());
Console.ReadKey();
}
}
}
參考資料: