C#:您建议如何重构这些类? (接口(interface)、聚合或其他任何东西)

标签 c# refactoring interface model

在两个不同的程序集中有以下类:

class Member
{
    public string Label {get;set;}
    // Lots of other fields...

    public double Thickness {get;set;}
    public double Width {get;set;}
    public double Length {get;set;}
    public double GetVolume ()
    {
        return Thickness * Width * Length;
    }

    // Other methods
}

class OtherMember
{
    public string CompositeLabel {get;set;}
    // Lots of other fields (not related to other class: Member)

    public double Thickness {get;set;}
    public double Width {get;set;}
    public double Length {get;set;}
    public double GetVolume ()
    {
        return Thickness * Width * Length;
    }

    // Other methods
}

我想将 Thickness、Width、Length 属性和 GetVolume 方法重构到另一个类(Dimensions?)至于 DRY...

然后我可以在这些类中有一个字段/属性来访问 Dimensions 实例。

这是一个好方法吗?

我已经简洁地阅读了关于使用接口(interface)而不是具体类的内容,我应该从接口(interface)继承吗?

另外,不变性呢?

我觉得我经常迷失在正确设置领域类方面。有人对此有什么建议吗?

最佳答案

由于你们有很多共同的状态和行为,我会推荐一个基类。尝试这样的事情:

class Member
{
    public string Label { get; set; }
    public double Thickness { get; set; }
    public double Width { get; set; }
    public double Length { get; set; }
    public double GetVolume()
    {
        return Thickness * Width * Length;
    }
}

class OtherMember : Member
{
    public string CompositeLabel { get; set; }
}

并且根据 Label 属性的用途,您可以选择将其设为虚拟并覆盖派生类中的实现:

class Member
{
    public virtual string Label { get; set; }
    public double Thickness { get; set; }
    public double Width { get; set; }
    public double Length { get; set; }
    public double GetVolume()
    {
        return Thickness * Width * Length;
    }
}

class OtherMember : Member
{
    string label;

    public override string Label
    {
        get { return this.label; }
        set { this.label = value; }
    }
}

关于C#:您建议如何重构这些类? (接口(interface)、聚合或其他任何东西),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1065106/

相关文章:

eclipse - Eclipse 支持的用于删除父类(super class)依赖性的重构可能是什么?

Java - 用户界面和终止

java - 在Java中实现CustomList的List接口(interface)

c# - 避免在 try/catch block 中出现警告 "variable is declared but never used"

c# - 用于在匹配引号之间选择数据的正则表达式模式

c# - 如何在windows右键菜单中添加自己的控件?

refactoring - Autofixture 生成自定义列表

c# - 为什么 ReadOnlySpan 不能用作泛型委托(delegate)和泛型方法的类型参数?

algorithm - 数字的分解优化

c# - 接口(interface) C# 中的可选空隙