我想在c ++ / cli
中转换此代码(c#中的工作代码) static private void onChange(object s, FileSystemEventArgs e, string customArg)
{
Console.WriteLine(e.FullPath);
Console.WriteLine(customArg);
}
static void Main(string[] args)
{
string customArg = "myCustomArg";
FileSystemWatcher watcher = new FileSystemWatcher();
watcher.Path = "G:\\";
watcher.IncludeSubdirectories = true;
watcher.NotifyFilter = NotifyFilters.LastWrite;
watcher.EnableRaisingEvents = true;
// i cannot convert this line in c++/cli
watcher.Changed += (s, e) => onChange(s, e, customArg);
Console.Read();
}
我的代码在c ++ / cli
中void FileWatcher::onChanged(Object^ source, FileSystemEventArgs^ e, String^ customArg)
{
Console::WriteLine(e->FullPath);
Console::WriteLine(customArg);
}
int main(int argc, char* argv[])
{
FileSystemWatcher watcher->Path = "G:\\";
watcher->IncludeSubdirectories = true;
watcher->NotifyFilter = static_cast<System::IO::NotifyFilters> (NotifyFilters::LastWrite);
String^ customArg = gcnew String("myArg");
// this line not compile
watcher->Changed += (s, e) = > onChange(s, e, customArg);
//
}
我试着像这样使用lambda函数
watcher->Changed += [](Object^ s, FileSystemEventArgs^ e, String^ c) -> void { OnChange(s, e, c); };
但它不起作用,可能做错了
答案 0 :(得分:1)
看起来你不能通过lambda这样做,所以你必须创建一个构成事件处理程序的类,类似于此。
#using <System.dll>
using namespace System;
using namespace System::IO;
void GlobalOnChanged(Object^ source, FileSystemEventArgs^ e, String^ customArg)
{
Console::WriteLine(e->FullPath);
Console::WriteLine(customArg);
}
public ref class Invoker
{
public:
Invoker(String^ customArg) : customArg_(customArg)
{
}
void OnChanged(Object^ source, FileSystemEventArgs^ e)
{
GlobalOnChanged(source, e, customArg_);
}
private:
String^ customArg_;
};
int main(int argc, char* argv[])
{
FileSystemWatcher^ watcher = gcnew FileSystemWatcher;
watcher->Path = "C:\\";
watcher->IncludeSubdirectories = true;
watcher->NotifyFilter = static_cast<System::IO::NotifyFilters> (NotifyFilters::LastWrite);
String^ customArg = gcnew String("myArg");
watcher->Changed += gcnew FileSystemEventHandler(gcnew Invoker(customArg), &Invoker::OnChanged);
}