如何使用param可选创建委托泛型?

时间:2019-08-05 05:47:07

标签: c# generics delegates

我尝试创建一个具有函数名称的函数-获得可选泛型参数的委托。

我的功能的目的是:听一个文件夹,当文件带有特定名称时,该文件夹将激活特定功能。 我搜索后发现,唯一的选择是两次编写代码。 我不想写两次代码,有谁知道如何做得更好?

代码:

public delegate void ActionFound<T>(T param);
public delegate void ActionNotFound<T>(T param);

public class FileListenerHelper
{

    public static void FileListener<T>(string folder, List<string> filesName, int waitingMinutes, ActionFound<T> found, T param, ActionNotFound<T> notFound = null)
    {
        if (filesName.SelectMany(f => Directory.GetFiles(folder, f + "*")).IsNotNullOrEmpty())
        {
            found(param);
            return;
        }
        bool ifNotRun = true;
        bool isStillRun = false;
        var completedEvent = new AutoResetEvent(false);

        var watcher = new FileSystemWatcher
        {
            Path = folder,
            NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite | NotifyFilters.DirectoryName | NotifyFilters.FileName
        };

        watcher.Created += (sender, args) =>
        {
            if (filesName.SelectMany(f => Directory.GetFiles(folder, f + "*")).IsNotNullOrEmpty())
            {
                isStillRun = true;
                ifNotRun = false;
                completedEvent.Set();
                found(param);
                isStillRun = false;
            }
        };
        watcher.EnableRaisingEvents = true;


        var startDate = DateTime.Now;
        var endDate = startDate.AddMinutes(waitingMinutes);
        var mi = HighResClock.CalcTimeSpan(startDate, endDate).TotalMilliseconds.ToInt();
        completedEvent.WaitOne(mi);

        while (isStillRun)
        {

        }

        if (ifNotRun && notFound.IsNotNull())
        {
            notFound(param);
            return;
        }
    }
}

0 个答案:

没有答案