【问题标题】:passing parameter to an event handler [duplicate]将参数传递给事件处理程序[重复]
【发布时间】:2012-12-27 17:08:30
【问题描述】:

我想使用我的事件将我的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)
{

}

【问题讨论】:

    标签: c# winforms


    【解决方案1】:

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

    【讨论】:

    • 顺便说一句,考虑从 EventArgs(或 EventArgs 层次结构中的其他合适的类)继承
    • 我已经添加了 :)thanx
    • 在我的课堂上,我正在使用 FileSystemWatcher 收听文件夹,在新文件到达后,我将此文件添加到我的列表中,然后触发我的事件,所以我应该已经有事件(公共事件 EventHandler _newFileEventHandler;),查看我的更新
    • 我知道,您应该将定义更改为公共事件 EventHandler _newFileEventHandler;添加新的“ListEventArgs”类后(注意:它应该继承自 EventArgs 类)
    • 我对您的 OnNewFileAdded 函数的工作方式做了一个小改动。如果您有一个多线程应用程序,并且最后一个调用者在 null 检查和委托调用之间取消订阅该事件,您将得到一个 NullRefrenceException。通过首先将委托复制到一个临时变量中,它可以防止这种情况发生。
    【解决方案2】:

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

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

    那么在订阅事件时:

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

    【讨论】:

      猜你喜欢
      • 2012-08-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-30
      • 2011-05-02
      相关资源
      最近更新 更多