我对事件的理解有问题。由于某些原因,我无法订阅我的活动。视觉工作室说
错误CS0029无法将类型'void'隐式转换为'FileSystemWatcher.FileSystemWatcher.Handler'FileSystemWatcher C:\ Users \ Diord \ source \ repos \ FileSystemWatcher \ FileSystemWatcher \ Program.cs 16活动
当我这样做
fileSystemWatcher.Changed + = ShowMessage();
class Program
{
static void Main(string[] args)
{
FileSystemWatcher fileSystemWatcher = new FileSystemWatcher("C:\\");
//next line is highlighted
fileSystemWatcher.Changed += ShowMessage();
}
public void ShowMessage()
{
Console.WriteLine("Hello Event!");
}
}
class FileSystemWatcher
{
readonly string _path;
private string[] Files { get; set; }
public FileSystemWatcher(string path)
{
_path = path;
}
public delegate void Handler();
public event Handler Changed;
}
Run Code Online (Sandbox Code Playgroud)
您必须从ShowMessage()中删除括号,因为这是在调用函数,而不是将方法“引用”到事件。
错误消息表明,“ void”(函数的结果)不能附加到事件中。
在代码中:
fileSystemWatcher.Changed += ShowMessage;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
35 次 |
| 最近记录: |