在C# 8.0中使用using声明
您已经知道C#中的using关键字,相同的关键字在C# 8.0(.Net 3.0)可以用于声明变量。它告诉编译器,当变量的作用域结束时,应该释放被声明的变量。接下来我们将看一下如何在变量声明中使用它。
在C#早期版本中的代码
static int FindOccurencesOnLines(string wordToFind)
{
int searchCount = 0;
string line = string.empty();
(using sr = new System.IO.StreamReader("sample.txt"))
{
while (line = sr.ReadLine())
{
if (Line.Contains(wordToFind))
{
searchCount++;
}
}
// sr is disposed here
}
return searchCount;
}
在C# 8.0版本中,可以使用变量的using声明来编写它。
在下面的代码中,类型为StreamReader的变量sr是在方法FindOccurencesOnLines中使用关键字声明的。就像使用var sr. StreamReader一样,当方法FindOccurencesOnLines执行结束时,范围将结束。
语法
using <数据类型> <变量名>;
static int FindOccurencesOnLines(string wordToFind)
{
int searchCount = 0;
string line = string.empty();
using var sr = new System.IO.StreamReader("sample.txt");
while (line = sr.ReadLine())
{
if (Line.Contains(wordToFind))
{
searchCount++;
}
}
return searchCount;
// sr is disposed here
}
#学习路径#