c# pass parameter to Action

六眼飞鱼酱① 提交于 2019-12-13 03:16:16

问题


I have the following code:

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());
    }
}

And this is the code in the consumer:

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

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

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

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?

Any help is appreciated!


回答1:


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



回答2:


Action is defined as delegate void Action(). Therefore, you cannot pass variables to it.

What you want is a Action<T, T2>, which exposes two parameters to be passed in.

Example usage.. feel free to apply it to your own needs:

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


// usage
action(Guid.NewGuid(), "Hello World!");


来源:https://stackoverflow.com/questions/19172405/c-sharp-pass-parameter-to-action

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!