C# 8.0 - Using declarations
نویسنده: وحید نصیری
تاریخ: ۱۳۹۸/۰۳/۱۳ ۱۱:۳۰
آدرس: www.dntips.ir
| مطالب | ۳۶۹۴ |
| نویسندگان | ۲۷۶ |
| گروههای مطالب | ۱۰۲۴ |
| نقشههای راه | ۱۱۹ |
| دورهها | ۱۴ |
| اشتراکها | ۱۷۹۱۴ |
class Program
{
static void UsingOld()
{
using (var file = new FileStream("input.txt", FileMode.Open))
using (var reader = new StreamReader(file))
{
var s = reader.ReadToEnd();
// Do something with data
}
} class Program
{
static void UsingNew(string[] args)
{
using Stream file = new FileStream("input.txt", FileMode.Open);
using StreamReader reader = new StreamReader(file);
var s = reader.ReadToEnd();
// Do something with data
} class Program
{
static void UsingNewScope()
{
string buffer = null;
using Stream file = new FileStream("input.txt", FileMode.Open);
using StreamReader reader = new StreamReader(file);
buffer = reader.ReadToEnd();
// Do something with data
buffer = null;
}
static void UsingOldScope(string[] args)
{
string buffer = null;
using (var file = new FileStream("input.txt", FileMode.Open))
using (var reader = new StreamReader(file))
{
buffer = reader.ReadToEnd();
}
// Do something with data
buffer = null;
} string buffer = null;
using (var file = new FileStream("input.txt", FileMode.Open))
{
using (var reader = new StreamReader(file))
{
buffer = reader.ReadToEnd();
buffer = null;
}
} private static void UsingDeclarationWithScope()
{
{
using var r1 = new AResource();
r1.UseIt();
} // r1 is disposed here!
Console.WriteLine("r1 is already disposed");
} public class AResource : IDisposable
{
public void UseIt() => Console.WriteLine(nameof(UseIt));
public void Dispose() => Console.WriteLine($"Dispose {nameof(AResource)}");
} class Program
{
public static AResource GetTheResource() => new AResource(); using (GetTheResource())
{
// do something here
} // resource is disposed here using GetTheResource(); // Compiler error
using var _ = GetTheResource(); // Works fine