C# 将参数传递给事件处理程序
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14058412/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
passing parameter to an event handler
提问by user1269592
i want to pass my List<string>
as parameter using my event
我想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);;
}
and from my main form i want to get this List:
从我的主要表格中我想得到这个列表:
void listener_newFileEventHandler(object sender, EventArgs e)
{
}
采纳答案by Sawan
Make a new EventArgs class such as:
创建一个新的 EventArgs 类,例如:
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)
}
回答by Servy
You can define the signature of the event to be whatever you want. If the only information the event needs to provide is that list, then just pass that list:
您可以将事件的签名定义为您想要的任何内容。如果事件需要提供的唯一信息是该列表,则只需传递该列表:
public event Action<List<string>> MyEvent;
private void Foo()
{
MyEvent(new List<string>(){"a", "b", "c"});
}
Then when subscribing to the event:
然后在订阅事件时:
public void MyEventHandler(List<string> list)
{
//...
}