I'm trying to create a form that will animate something while processing a particular task (passed as a delegate to the constructor). It's working fine, but the problem I'm having is that I can't instantiate a copy of my generic class if the particular method that I want to perform has a return type of void.
I understand that this is by design and all, but I'm wondering if there is a known workaround for situations like this.
If it helps at all my windows form looks like so (trimmed 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 like:
operatingWindow<int> processing = new operatingWindow<int>(new operatingWindow<int>.Operation(this.doStuff));
processing.ShowDialog();
// ...
private int doStuff()
{
Thread.Sleep(3000);
return 0;
}
Currently, void is not allowed as a generic parameter for a type or a method, what makes it hard in some cases to implement a common logic for a method, that's why we have Task and Task<T> for instance.
You cannot inherit a generic type. // class Derived20 : T {}// NO!
Yes, you can define a generic method in a non-generic class in Java.
Whenever you want to restrict the type parameter to subtypes of a particular class you can use the bounded type parameter. If you just specify a type (class) as bounded parameter, only sub types of that particular class are accepted by the current generic class.
No, you'll need to create an overload to do that.
e.g.
public operatingWindow(Action action)
{
m_Operation=() => { action(); return null; }
}
Also you don't need to define your own delegate, you can use Func<T>
and Action.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With