zoukankan      html  css  js  c++  java
  • passing parameter to an event handler [stackoverflow]

    Q:

    i want to pass my List<string> as parameter using my event

    public event EventHandler _newFileEventHandler;
        List<string> _filesList = new List<string>();
    
    public void startListener(string directoryPath)
    {
        FileSystemWatcher watcher = new FileSystemWatcher(directoryPath);
        _filesList = new List<string>();
        _timer = new System.Timers.Timer(5000);
        watcher.Filter = "*.pcap";
        watcher.Created += watcher_Created;            
        watcher.EnableRaisingEvents = true;
        watcher.IncludeSubdirectories = true;
    }
    
    void watcher_Created(object sender, FileSystemEventArgs e)
    {            
        _timer.Elapsed += new ElapsedEventHandler(myEvent);
        _timer.Enabled = true;
        _filesList.Add(e.FullPath);
        _fileToAdd = e.FullPath;
    }
    
    private void myEvent(object sender, ElapsedEventArgs e)
    {
        _newFileEventHandler(_filesList, EventArgs.Empty);;
    }

    and from my main form i want to get this List:

    void listener_newFileEventHandler(object sender, EventArgs e)
    {
    
    }
    A:

    Make a new EventArgs class such as:

    public class ListEventArgs : EventArgs
        {
            public List<string> Data { get; set; }
            public ListEventArgs(List<string> data)
            {
                Data = data;
            }
        }

    And make your event as this:

    public event EventHandler<ListEventArgs> NewFileAdded;

    Add a firing method:

    protected void OnNewFileAdded(List<string> data)
    {
        var localCopy = NewFileAdded;
        if (localCopy != null)
        {
            localCopy(this, new ListEventArgs(data));
        }
    }

    And when you want to handle this event:

    myObj.NewFileAdded += new EventHandler<ListEventArgs>(myObj_NewFileAdded);

    The handler method would appear like this:

    public void myObj_NewFileAdded(object sender, ListEventArgs e)
    {
           // Do what you want with e.Data (It is a List of string)
    }
  • 相关阅读:
    进程和阻塞
    docker简介
    python===lambda匿名函数===day15
    python----生成器, 生成器函数, 推倒式---13
    python----函数参数---10天
    python---函数 第九天
    python===文件===第八天
    python===基本数据类型 基本增删改查 ===深浅拷贝==第七天
    20180802 (个别内置方法)
    20180730 (面向对象的反射,内置方法)
  • 原文地址:https://www.cnblogs.com/czytcn/p/7887138.html
Copyright © 2011-2022 走看看