Passing a void to a common class

I am trying to create a form that will animate something while processing a specific task (passed as a delegate to the constructor). It works fine, but the problem is that I cannot create an instance of my generic class if the specific method that I want to execute has a return type of void.

I understand that this is by design and all, but I wonder if there is a well-known workaround for such situations.

If this helps, then my window shape looks like this (cropped for brevity):

public partial class operatingWindow<T> : Form
{
    public delegate T Operation();
    private Operation m_Operation;

    private T m_ReturnValue;
    public T ValueReturned { get { return m_ReturnValue; } }

    public operatingWindow(Operation operation) { /*...*/ }
}

And I call it that:

operatingWindow<int> processing = new operatingWindow<int>(new operatingWindow<int>.Operation(this.doStuff));
processing.ShowDialog();

// ... 
private int doStuff()
{
    Thread.Sleep(3000);

    return 0;
}
+5
source share
2 answers

I would review your design a bit.

, , .

, , . ( , Func<T> , .

. // .. . , .

:

private void DoSleep()
{
    Thread.CurrentThread.Sleep(5000);
}
private int ReturnSleep()
{
    Thread.CurrentThread.Sleep(5000);
    return 5000;
}
...
{
    var actionWindow = new OperatingWindowAction(this.DoSleep);
    actionWindow.Execute();
    var funcWindow = new OperatingWindowFunc<int>(this.ReturnSleep);
    funcWindow.Execute();
    int result = funcWindow.Result;
}

:

public abstract partial class OperatingWindowBase : Form
{
    public void Execute()
    {
        // call this.OnExecute(); asyncronously so you can animate
    }
    protected abstract void OnExecute();
}

public class OperatingWindowFunc<T> : OperatingWindowBase
{
    Func<T> operation;
    public T Result { get; private set; }
    public OperatingWindowFunc<T>(Func<T> operation)
    {
        this.operation = operation;
    }
    protected override OnExecute()
    {
        this.Result = operation();
    }
}

public class OperatingWindowAction
{
    Action operation;
    public OperatingWindow(Action operation)
    {
        this.operation = operation;
    }
    protected override OnExecute()
    {
        operation();
    }
}
+4

, , .

.

public operatingWindow(Action action) 
{ 
    m_Operation=() => { action(); return null; }
}

, Func<T> .

+6

All Articles