c# - 实现一个接口(interface),泛型基于该接口(interface)

标签 c# generics interface refactoring

我目前正在重构我的代码,以便所有重要的类都实现一个接口(interface)(用于单元测试)。我遇到了一个实现 IComparable(非模板化)的类;像这样的东西:

public MyClass : IComparable
{
    public int CompareTo(object obj)
    {
        MyClass cObj = obj as MyClass;
        if (cObj == null) { throw new ArgumentException(); }
        // etc.
    }
}

我想把它连接起来,并在我使用它的时候使用泛型;像这样:

public IMyClass : IComparable<IMyClass>
{
    // Other methods here
}

public MyClass : IMyClass
{
    public CompareTo<IMyClass>(IMyClass other)
    {
        ...
    }
    // Other methods here
}

但是,理想情况下,MyClass应该实现 IComparable<MyClass> (然后 MyClass 的子类应该实现 IComparable<MySubClass> )。

所有这些都是为了问几个问题:

您如何看待我描述的方法?有没有更好的方法来进行这种重构?制作MyClass是否有意义?还执行 IComparable<MyClass> ,或者那是没有意义的,因为我们已经实现了 IComparable<IMyClass> ?我可以了解任何专业提示或“最佳”实践吗?

最佳答案

拥有多个不同类型的对象并且都可以相互比较真的有意义吗?该语言允许这样做,但我可以指望 0 次我必须使用它的次数。

我建议使用 IClass 而不是 IComparable,并且只让派生类实现 IComparable

附言我也反对添加“用于单元可测试性”的接口(interface)。如果您的程序设计需要具有仅接口(interface)耦合的工厂模式,那么一定要编写复杂程度更高的代码。但是不要abuse the design只是为了让你的测试更容易;请改用 Moles。

关于c# - 实现一个接口(interface),泛型基于该接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5958331/

相关文章:

Java类方法没有初始化

c# - 为什么实现 'IList<T>' 需要定义两个 'GetEnumerator' 方法?

c# - 使用命令将 BMP 文件打印到打印机

c# - 如何从 XmlDocument 中删除空格

generics - TypeScript 中的关联类型

c++ - 在模板类中重载下标运算符

c# - MVC 4 后期绑定(bind) DataContext 实体 LINQ 引用

c# - 如何在 xamarin 中获得焦点 VisualElement?

swift - 获取错误 : String is not convertible to 'T'

winforms - C++/CLI : How to control WinForms from main function?