【问题标题】:c# pass parameter to Actionc#将参数传递给Action
【发布时间】:2013-10-04 02:51:59
【问题描述】:

我有以下代码:

public partial class WaitScreen : Form
{
    public Action Worker { get; set; }

    public WaitScreen(Action worker)
    {
        InitializeComponent();

        if (worker == null)
            throw new ArgumentNullException();

        Worker = worker;
    }

    protected override void OnLoad(EventArgs e)
    {
        base.OnLoad(e);

        Task.Factory.StartNew(Worker).ContinueWith(t => { this.Close(); }, TaskScheduler.FromCurrentSynchronizationContext());
    }
}

这是消费者中的代码:

private void someButton_Click(object sender, EventArgs e)
{
    using (var waitScreen = new WaitScreen(SomeWorker))
        waitScreen.ShowDialog(this);
}

private void SomeWorker()
{
    // Load stuff from the database and store it in local variables.
    // Remember, this is running on a background thread and not the UI thread, don't touch controls.
}

现在,我必须在 Action "SomeWorker" 中添加一个参数,例如:

private void SomeWorker(Guid uid, String text)
    {
        // here will execute the task!!
    }

如何将参数 uidtext 传递给 Action?

是否可以使其通用,以便我可以传递任何参数,以便它可以处理任何数量和类型的参数?

感谢任何帮助!

【问题讨论】:

    标签: c# multithreading winforms backgroundworker


    【解决方案1】:

    对于这种情况,我认为您不能使用Action<Guid, string>,因为我看不到您如何将参数传递给新表单。您最好的选择是使用匿名委托来捕获您要传入的变量。您仍然可以将函数分开,但您需要匿名委托来进行捕获。

    private void someButton_Click(object sender, EventArgs e)
    {
        var uid = Guid.NewGuid();
        var text = someTextControl.Text;
    
        Action act = () => 
            {
                //The two values get captured here and get passed in when 
                //the function is called. Be sure not to modify uid or text later 
                //in the someButton_Click method as those changes will propagate.
                SomeWorker(uid, text)
            }
        using (var waitScreen = new WaitScreen(act))
            waitScreen.ShowDialog(this);
    }
    
    private void SomeWorker(Guid uid, String text)
    {
        // Load stuff from the database and store it in local variables.
        // Remember, this is running on a background thread and not the UI thread, don't touch controls.
    }
    

    【讨论】:

      【解决方案2】:

      Action 定义为delegate void Action()。因此,您不能将变量传递给它。

      你想要的是一个Action<T, T2>,它公开了两个要传入的参数。

      示例用法..随意将其应用于您自己的需要:

      Action<Guid, string> action = (guid, str) => {
          // guid is a Guid, str is a string.
      };
      
      
      // usage
      action(Guid.NewGuid(), "Hello World!");
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多