using in .NET
using 的使用并不少见,但是最近看到这种用法还是觉得有些奇怪:
1 static IEnumerable<int> LoadNumbers(string filePath) 2 { 3 using StreamReader reader = File.OpenText(filePath); 4 5 var numbers = new List<int>(); 6 string line; 7 while ((line = reader.ReadLine()) is not null) 8 { 9 if (int.TryParse(line, out int number)) 10 { 11 numbers.Add(number); 12 } 13 } 14 return numbers; 15 }
如上面的代码示例,using并没有带大括号,微软的文档说明是:
When declared in a using
declaration, a local variable is disposed at the end of the scope in which it's declared. In the preceding example, disposal happens at the end of a method.
A variable declared by the using
statement or declaration is readonly. You cannot reassign it or pass it as a ref or out parameter.
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/statements/using