C# yield 按需返回
在方法中按需返回数据,而不需要一次性把所有数据加载到内存中,处理大量数据或需要懒加载(lazy loading)时特别有用
string filePath = @""; // 假设这是一个很大的文件路径
var ss = ReadLargeFile(filePath);
foreach (var line in ss)
{
Console.WriteLine(line);
}
// 使用 yield 模拟从大文件中按需读取数据
static IEnumerable<string> ReadLargeFile(string filePath)
{
using (StreamReader reader = new StreamReader(filePath))
{
string line;
while ((line = reader.ReadLine()) != null)
{
// 每次返回一行数据,直到文件结束
yield return line;
}
}
}
Console.ReadKey();

浙公网安备 33010602011771号