, :
using (var fileStream = new FileStream(@"C:\temp\test.txt", FileMode.Open))
{
var bytes = new byte[fileStream.Length];
fileStream.Read(bytes, 0, (int)fileStream.Length);
var text = Encoding.Default.GetString(bytes);
Console.WriteLine(text);
}
, IDisposable; DataContext. , , using; :
Read(fileStream =>
{
var bytes = new byte[fileStream.Length];
fileStream.Read(bytes, 0, (int)fileStream.Length);
var text = Encoding.Default.GetString(bytes);
Console.WriteLine(text);
}, @"C:\temp\test2.txt");
static void Read(Action<FileStream> action, string path)
{
using (var fileStream = new FileStream(path, FileMode.Open))
{
action(fileStream);
}
}
Here you enter the code you want to execute, ensuring that the statement usingis removed from the method. In addition, you can guarantee that the instruction usingwill be used. The output of this program will be as expected:
Hello, World!
Hello, World; from an injected function!
Press any key to continue . . .
source
share