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

时间:2012-12-27 17:08:30

标签: c# winforms

我希望使用我的活动

传递我的List<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)
{

}

2 个答案:

答案 0 :(得分:57)

创建一个新的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)
}

答案 1 :(得分:4)

您可以将事件的签名定义为您想要的任何内容。如果事件需要提供的唯一信息是该列表,那么只需传递该列表:

public event Action<List<string>> MyEvent;

private void Foo()
{
     MyEvent(new List<string>(){"a", "b", "c"});
}

然后订阅活动时:

public void MyEventHandler(List<string> list)
{
    //...
}