I'm having a hard time to implement an Api for my Datastructure in C# using generics. Here's what I want to achieve:
static void Main(string[] args) {
Enterprise google = new Enterprise();
new ConverterChain<Enterprise>(google)
.convert(enterprise => enterprise.getWorkers())
.convert(worker => worker.getAddresses())
.doAction(address => Debug.Log(address.getStreet()));
}
The fictional simplified example code does the following:
- find all workers for google and display them on GUI
- wait for user to select one worker
- find all addresses for the selected worker and display them on GUI
- wait for user to select one address
- find all streets for the selected address and display them on GUI
- wait for user to select one street and do some action with that street (i.e. write it to log)
As I want to do some asyncronous stuff I need to store all the Func
s and Action
s in one datastructure for further execution. In order to have a nice Api I need to use generics. Here's what I have until now:
public class ConverterChain<I> {
I input;
public ConverterChain(I input) {
this.input = input;
}
public Converter<I, O> convert<O>(Func<I, List<O>> c) {
return new Converter<I, O>(c);
}
}
public class Converter<I, O> {
public Func<I, List<O>> c { get; private set; }
public Converter(Func<I, List<O>> c) {
this.c = c;
}
public Converter<O, N> convert<N>(Func<O, List<N>> c) {
return new Converter<O, N>(c);
}
public void doAction(Action<O> action) {
// and now bring somehow all converters into a single structure
}
}
Coming from Java I would do something like that:
public void doAction(Action<O> action) {
List<Converter<?, ?>> allConverters = getConvertersFromParents();
object rootObject = getInputFromRoot();
GUIHandler.doComplicatedAsynchronousStuff(rootObject, allConverters, action);
}
Without Converter<?, ?>
no matter how I implement those data structures, I don't get the step done to convert all the Lambdas into one data structure. I fail to create the parent-child structure in Converter<I, O>
in a clean generic way as each converter has different I
s and O
s.
Using something like Converter<object, object>
fails as for whatever reason
Converter<I, O> myConverter = ...
Converter<object, object> genericConverter = (Converter<object, object>) myConverter;
is not allowed.
What is the C# way to implement my given scenario?