本文介绍了c#将参数传递给Action的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码:

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.
}

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

Now, I have to add a paramter to Action "SomeWorker", for example:

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

如何将参数 uid text 传递给操作?

How can I pass the parameters uid and text to the Action?

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

Is it possible to make it generic so I can pass any parameter so It can work with any amount and types of params?

感谢您的帮助!

推荐答案

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

For this kind of situation I don't think you could use a Action<Guid, string> as I can't see how you would pass the parameters in to the new form in the first place. Your best option is use a anonymous delegate to capture the variables you want to pass in. You can still keep the function separate but you will need the anonymous delegate for the capture.

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.
}

这篇关于c#将参数传递给Action的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 10:46
查看更多