字段初始值设定项不能引用EventHandler中的非静态字段、方法或属性



我在第行收到以下错误(字段初始值设定项不能引用EventHandler中的非静态字段、方法或属性(:

FilesFound = FilesFound + 1;

有人知道为什么以及会有什么解决办法吗?

public class FileSearcher
{
public event EventHandler<FileFoundArgs> FileFound;
public int FilesFound { get; set; } = 0;

EventHandler<FileFoundArgs> onFileFound = (sender, eventArgs) =>
{
Console.WriteLine(eventArgs.FoundFile);
FilesFound = FilesFound + 1;
};

public FileSearcher()
{
FileFound += onFileFound;
}
public void Search(string directory, string searchPattern)
{
foreach (var file in Directory.EnumerateFiles(directory, searchPattern))
{
FileFound?.Invoke(this, new FileFoundArgs(file));
}
}
}

感谢

错误消息准确地说明了问题所在——字段初始值设定项通过lambda表达式使用实例成员(FilesFound(。不能在实例字段初始值设定项中引用其他实例成员。

简单的修复方法是将初始化转移到构造函数:

private EventHandler<FileFoundArgs> onFileFound;
public FileSearcher()
{
onFileFound = (sender, eventArgs) =>
{
Console.WriteLine(eventArgs.FoundFile);
FilesFound = FilesFound + 1;     
};
FileFound += onFileFound;
}

或者,如果您不打算在其他任何地方使用onFileFound,请将其完全作为一个字段删除,然后直接订阅构造函数中的事件:

private EventHandler<FileFoundArgs> onFileFound;
public FileSearcher()
{
FileFound += (sender, eventArgs) =>
{
Console.WriteLine(eventArgs.FoundFile);
FilesFound = FilesFound + 1;     
};
}

最新更新