我正在处理一段旧代码,并试图通过 .NET 的新进展重新实现它。然而,我不能把我的头绕在这个设计上。以前没有模板类/接口,现在我需要使用它们。我将尝试举一个设计示例以及我遇到困难的地方。设计是这样的:
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);
}
我不能更改接口实现,因为我不是它的所有者。但正如评论显示的那样,我会在 处出错w1.WorkOnInput(this)
,因为这里需要Input
类型而不是Input<T>
。
但是,如果我将 更改WorkOnInput
为接受类型的参数,Input<T>
那么我将不得不将其设为通用方法,因为WorkOnInput<T>
如果我需要调用它,我将显式地提供输入的类型,这也是不可取的。
另外,我有一个需要传递的输入列表,AnotherMethod()
而 aList<Input<T>>
是不可能的。
我想我对这个场景有点太困惑了,并且在没有任何具体解决方案的情况下转来转去。
有人可以指出我正确的方向吗?