【问题标题】:Class Design with Generic Class and Interface in C#在 C# 中使用泛型类和接口进行类设计
【发布时间】: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&lt;T&gt;

但是,如果我将WorkOnInput 更改为接受Input&lt;T&gt; 类型的参数,那么我将不得不将其设为WorkOnInput&lt;T&gt; 的通用方法,如果我需要调用它,我将必须明确提供类型的输入也是不可取的。

我还有一个需要传递给AnotherMethod() 的输入列表,而List&lt;Input&lt;T&gt;&gt; 是不可能的。

我觉得我对这个场景有点太困惑了,并且在没有任何具体解决方案的情况下四处走动。

有人可以指出我正确的方向吗?

【问题讨论】:

  • 不应该 class Input&lt;T&gt; : Service&lt;T&gt;, Inputclass Input&lt;T&gt; : Input, Service&lt;T&gt; 吗? ...如果可以,您应该将Service&lt;T&gt; 重命名为IService&lt;T&gt;
  • 你试过w1.WorkOnInput((Input)this);吗?
  • 所以创建一个public class TList&lt;T&gt; : List&lt;Input&lt;T&gt;&gt; {}
  • 首先,再次阅读@CharlesBretana 评论的第一部分。这不仅仅是关于编码约定。如果在接口之前不指定基类,上面的代码根本无法编译。其次,无论是否通用,Input 都可以隐式转换为 Input,因此上面的代码应该可以工作。您最好显示Worker 类的外观以及您遇到的确切编译器错误。
  • 我犯了巨大的错误,我向@CharlesBretana 道歉,我错过了您评论的第一个也是更重要的部分。您能否将此添加为答案,以便我可以将其标记为答案。@Ivan Stoev 谢谢您的大开眼界。

标签: c# generics class-design generic-interface


【解决方案1】:

class Input&lt;T&gt; : Service&lt;T&gt;, Input 不应该是 class Input&lt;T&gt; : Input, Service&lt;T&gt; 吗?

...如果可以的话,您应该将Service&lt;T&gt; 重命名为IService&lt;T&gt; - 它是一个接口而不是一个类。通过遵循最佳实践命名约定,它将使写作

class Input<T> : IService<T>, Input

明显错误,导致接口依赖列在唯一允许的基类之前。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多