在两个不同的程序集中有以下类:
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/