gpt4 book ai didi

c# - 将事件处理程序的定义作为 lambda 表达式传递

转载 作者:行者123 更新时间:2023-11-30 23:14:16 28 4
gpt4 key购买 nike

static void Main(string[] args)
{
Watcher w = new Watcher();
w.watch(@"someLocation", (() => { MoveFiles.Move() ; return 0; }));
}

public void watch(string pathName, Func< int> OnChanged)
{
FileSystemWatcher watcher = new FileSystemWatcher();
watcher.Path = pathName;
watcher.Filter = "*.*";
watcher.Created += new FileSystemEventHandler(OnChanged);
watcher.EnableRaisingEvents = true;
Console.WriteLine("Press \'q\' to quit the sample.");
while (Console.Read() != 'q') ;
}

我正在尝试传递 OnChanged 的定义事件作为 lambda 表达式,但我得到了

Error: No Overload for Func matches the delegate "System.IO.FileSystemEventHandle"

我尝试更改委托(delegate) Func<int>Func<Object, FileSystemEventArgs, int>但仍然会出现一些错误。

请指教。

最佳答案

FileSystemEventHandler delegate 正好有两个参数 - sender objectFileSystemEventArgs争论。而且它不返回任何值。 IE。它的签名看起来像:

public void FileSystemEventHandler(object sender, FileSystemEventArgs e)

Lambda 应该匹配这个签名——它不应该返回任何值并且它应该接受如上所述的两个参数。您可以使用 FileSystemEventHandlerAction<object, FileSystemEventArgs>委托(delegate)作为方法参数:

public void watch(string pathName, FileSystemEventHandler OnChanged)
{
// ...
watcher.Created += OnChanged;
}

将 lambda 传递给此方法:

w.watch(@"someLocation", (s,e) => MoveFiles.Move());

注意:FileSystemEventHandler之间没有隐式转换和 Action<object, FileSystemEventArgs>委托(delegate)们。因此,如果您将使用 Action<object, FileSystemEventArgs> 的处理程序类型,那么你应该这样附加它:

watcher.Created += new FileSystemEventHandler(OnChanged);

关于c# - 将事件处理程序的定义作为 lambda 表达式传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43195872/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com