加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 将参数传递给事件处理程序

发布时间:2020-12-15 06:46:19 所属栏目:百科 来源:网络整理
导读:参见英文答案 C# passing extra parameters to an event handler?8个 我想通过我的列表 string作为使用我的事件的参数 public event EventHandler _newFileEventHandler; Liststring _filesList = new Liststring();public void startListener(string direct
参见英文答案 > C# passing extra parameters to an event handler?8个
我想通过我的列表< string>作为使用我的事件的参数
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);;
}

从我的主要形式我想得到这个列表:

void listener_newFileEventHandler(object sender,EventArgs e)
{

}

解决方法

创建一个新的EventArgs类,如:
public class ListEventArgs : EventArgs
    {
        public List<string> Data { get; set; }
        public ListEventArgs(List<string> data)
        {
            Data = data;
        }
    }

并使您的活动如下:

public event EventHandler<ListEventArgs> NewFileAdded;

添加射击方法:

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

当你想处理这个事件时:

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

处理程序方法将如下所示:

public void myObj_NewFileAdded(object sender,ListEventArgs e)
{
       // Do what you want with e.Data (It is a List of string)
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读