【发布时间】:2015-09-24 11:53:23
【问题描述】:
我正在编写一段旧代码,并尝试利用 .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() 的输入列表,而List<Input<T>> 是不可能的。
我觉得我对这个场景有点太困惑了,并且在没有任何具体解决方案的情况下四处走动。
有人可以指出我正确的方向吗?
【问题讨论】:
-
不应该
class Input<T> : Service<T>, Input是class Input<T> : Input, Service<T>吗? ...如果可以,您应该将Service<T>重命名为IService<T> -
你试过
w1.WorkOnInput((Input)this);吗? -
所以创建一个
public class TList<T> : List<Input<T>> {} -
首先,再次阅读@CharlesBretana 评论的第一部分。这不仅仅是关于编码约定。如果在接口之前不指定基类,上面的代码根本无法编译。其次,无论是否通用,Input
都可以隐式转换为 Input,因此上面的代码应该可以工作。您最好显示 Worker类的外观以及您遇到的确切编译器错误。 -
我犯了巨大的错误,我向@CharlesBretana 道歉,我错过了您评论的第一个也是更重要的部分。您能否将此添加为答案,以便我可以将其标记为答案。@Ivan Stoev 谢谢您的大开眼界。
标签: c# generics class-design generic-interface