c# 将参数传递给操作

本文关键字:操作 参数传递 | 更新日期: 2023-09-27 18:33:46

我有以下代码:

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"添加一个参数,例如:

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

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

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

任何帮助不胜感激!

c# 将参数传递给操作

对于这种情况,我认为您不能使用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.
}

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!");