Reputation: 91
I am working on an old piece of code and trying to implement it afresh with the new advancements in .NET. However I can't wrap my head around the design for the same. Previously there were no template classes/interfaces and now I need to make use of the same. I will try to give an example of the design and where I am getting stuck. The design is something like this :
interface Service<T>
{
T Value;
Task AsyncWork();
}
class Input<T> : Service<T>, Input
{
Worker w1;
Task AsyncWork()
{
w1.WorkOnInput(this); //error
... //will return a Task eventually
}
}
class Input
{
//common members and methods for child classes
int priority;
string Name;
FormatInput()
{
//some common implementation
}
}
class StringInput:Input<string>
{
//Implementation specific to string input
}
class IntInput:Input<int>
{
//Implementation specific to int input
}
class Worker
{
WorkOnInput(Input)
{
...
}
}
Main()
{
Worker w = new Worker();
Input input1 = new StringInput();
Input input2 = new IntInput();
input1.FormatInput();
input2.FormatInput();
List<Input> inputList = new List<Input>();
inputList.Add(input1);
inputList.Add(input2);
AnotherMethod(inputList); //another method which expects a list of Inputs
w.WorkOnInput(input1);
w.WorkOnInput(input2);
}
I cannot change the interface implementation as I am not the owner of the same. But as the comment shows I would have an error at w1.WorkOnInput(this)
, since this here expects Input
type and not Input<T>
.
However if I change the WorkOnInput
to accept an argument of type Input<T>
then I would have to make it a generic method as WorkOnInput<T>
and if I would need to call it I would explicitly have to provide the type of the input which is also not desirable.
Also I have a list of inputs which is needed to be passed to AnotherMethod()
and a List<Input<T>>
is not possible.
I think I am getting a bit too confused with the scenario and am going round and round without any concrete solution.
Can someone please point me into the right direction?
Upvotes: 0
Views: 562
Reputation: 146499
Shouldn't class Input<T> : Service<T>, Input
be class Input<T> : Input, Service<T>
?
... and if you can, you should rename Service<T>
as IService<T>
- It is an interface not a class. By following best practice naming conventions, it would make writing
class Input<T> : IService<T>, Input
clearly and obviously wrong, cause the interface dependency is listed before the one and only allowed base class.
Upvotes: 2