gpt4 book ai didi

c# - 如何正确引发自定义事件?

转载 作者:行者123 更新时间:2023-11-30 16:25:18 32 4
gpt4 key购买 nike

我需要一个自定义事件,如果发现/创建特定目录中的新文件/现有文件,该事件应该引发。为了检查是否创建了新文件,我使用了 SystemFileWatcher,它工作正常。为了检查程序启动时是否存在某些文件,我写了一些行并且可以正常工作。

我将此类用于事件参数:

public class FileDetectEventArgs : EventArgs
{
public String Source { get; set; }
public String Destination { get; set; }
public String FullName { get; set; }

public FileDetectEventArgs(String source, String destination, String fullName)
{
this.Source = source;
this.Destination = destination;
this.FullName = fullName;
}
}

如果 SystemFileWatcher 引发 FileCreated 事件,我将使用这些代码行:

public void onFileCreated(object sender, FileSystemEventArgs e)
{
// check if file exist
if (File.Exists(e.FullPath))
{
OnNewFileDetect(new FileDetectEventArgs(source, destination, e.FullPath));
}
}

如果文件存在,我会尝试以这种方式引发事件:

public void checkExistingFiles(String source, String filter)
{
DirectoryInfo di = new DirectoryInfo(source);
FileInfo[] fileInfos = di.GetFiles();
String fileFilter = filter.Substring(filter.LastIndexOf('.'));

foreach (FileInfo fi in fileInfos)
{
if (fi.Extension.Equals(fileFilter))
{
OnNewFileDetect(new FileDetectEventArgs(source, destination, fi.FullName));
}
}
}

这是 OnNewFileDetect 事件:

protected void OnNewFileDetect(FileDetectEventArgs e)
{
if (OnNewFileDetectEvent != null)
{
OnNewFileDetectEvent(this, e);
}
}

问题是,如果 onFileCreated-Event 引发我的 OnNewFileDetect-Event 一切正常。但是,如果 checkExistingFiles 找到了一些现有文件并尝试引发 OnNewFileDetect-Event,则什么也不会发生。我发现 OnNewFileDetectEvent-Object 为空,因此什么也没有发生。但是,如果 onFileCreated-Event 被触发,为什么它不为空?

最佳答案

But why its not null if the onFileCreated-Event is fired?

在有人订阅该事件之前,该事件将为空。


附带说明一下,我会考虑切换到更好的模式来引发事件,并在此处使用标准 C#/.NET 命名。这更像是:

// The event...
public EventHandler<FileDetectedEventArgs> NewFileDetected;

// Note the naming
protected void OnNewFileDetected(FileDetectedEventArgs e)
{
// Note this pattern for thread safety...
EventHandler<FileDetectedEventArgs> handler = this.NewFileDetected;
if (handler != null)
{
handler(this, e);
}
}

关于c# - 如何正确引发自定义事件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10098000/

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