0

我有以下代码:

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?

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

任何帮助表示赞赏!

4

2 回答 2

1

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

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

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

Action<Guid, string> action = (guid, str) => {
    // guid is a Guid, str is a string.
};


// usage
action(Guid.NewGuid(), "Hello World!");
于 2013-10-04T03:06:30.757 回答
1

对于这种情况,我认为您不能使用 a 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.
}
于 2013-10-04T03:06:58.020 回答