C# 向事件操作传递附加参数;

C# 向事件操作传递附加参数;,c#,.net,events,action,C#,.net,Events,Action,进度的定义已更改: // Summary: // Event called whenever the progress of the upload changes. public event Action<IUploadProgress> ProgressChanged; public void insertFile(String filePath) { //.. some code insertRequest.ProgressChanged += Upload_P

进度的定义已更改

// Summary:
// Event called whenever the progress of the upload changes.
public event Action<IUploadProgress> ProgressChanged;

public void insertFile(String filePath)
{
    //.. some code
    insertRequest.ProgressChanged += Upload_ProgressChanged;
}

public void Upload_ProgressChanged(Google.Apis.Upload.IUploadProgress progress)
{          
     //.. I need filePath from insertFile() here!
}

我犯了一个错误,
无法将类型“void”隐式转换为“System.Action”

而不是使用事件,您可以在闭包中捕获变量

insertRequest.ProgressChanges += progress => { /* Do something with filePath here */ };

首先,定义EventArgs类-这将让您拥有任何您喜欢的信息

public class ProgressChgEventArgs : System.EventArgs
{
    public string Name { get;set; }
    public int InstanceId { get;set; }

    public ProgressChgEventArgs(string name, int id)
    {
        Name = name;
        InstanceId = id;
    }
}
接下来,创建使用这些参数的事件:

public event EventHandler<ProgressChgEventArgs> ProgressChanged;

我会在这里遵循事件模式…@AdrianoRepetti他已经是了…我会使用标准事件模式:您声明了
ProgressChangedEventArgs
?很好,现在让我们将事件从
Action
更改为
EventHandler
。顺便说一句,不要每次(重新)注册事件处理程序。基本上就是barrick在回答中所说的(在我看来,这更正确,即使它意味着一些重构),在
EventArgs
类中添加您需要的任何内容。捕获一个变量也是可行的(如果您不需要在类外公开该事件,也不想在不同的类中拆分代码,那么这是绝对可行的),但您必须理解它的含义。@AdrianoRepetti确实做到了。从一开始,整个问题就是如何允许事件处理程序在附加事件处理程序时访问范围内的变量,这正是您最后的评论完全不合适的原因,因为定义事件时该变量不在范围内,您建议删除触发事件时公开的信息。@Servy“我做了以下操作:”仍然缺少部分:假设
ProgressChanged
位于另一个对象中,并且
fileName
必须传递给它的某个方法以…实际执行上载,然后是,我将使用
EventHandler
更改
操作
,并在那里添加相关信息。没有捕获,当然我不会为每次调用
insertFile()
添加新的事件处理程序。对不起,您能解释更多细节吗?如果您能帮助我,我会很高兴。处理程序中需要的变量是在添加事件处理程序时当前在作用域内的变量,而不是在触发事件时,因此这完全是错误的想法。OP没有要求使用eventargs替换方法。谢谢,这很有效。但我真的不明白为什么。用事件做它的替代方法是什么?@user3715778这是解决问题的正确方法,它使用事件来解决它。
public event EventHandler<ProgressChgEventArgs> ProgressChanged;
public void OnProgressChanged(ProgressChgEventArgs e)
{
    var handler = new EventHandler<ProgressChgEventArgs>();
    if (handler != null)
        handler(this, e);
}
private void Progress(string caller, int callerId)
{
    var arguments = new ProgressChgEventArgs(caller, callerId);
    OnProgressChanged(arguments);
}