重构公共代码的最佳方式

本文关键字:最佳 方式 代码 重构 | 更新日期: 2023-09-27 18:13:32

考虑以下两个从接口实现一系列属性的类:

界面代码:

public interface ISample
{
    int x;
    string y;
}
类1:

public class SampleA: ISample
{
    public int x { get; set; }
    public string y { get; set; }
}
类2:

public class SampleB: ISample
{
    public int x { get; set; }
    [Decorated]
    public string y { get; set; }
}

这里唯一的区别是SampleB有一个属性装饰了一个属性。

这是高度简化的,所讨论的类有更多的属性,但主要的区别是一个类有一些用属性装饰的属性。

将来会有这样的情况,将来会引入实现ISample接口的更多类,并且感觉这些类可能应该从抽象类或其他东西继承一些通用代码。

重构这段代码的好方法是什么?

重构公共代码的最佳方式

试试这个解决方案:Sample类的所有属性都将是virtual,如果你想在派生类中用属性装饰它们中的一些,只需override它们。

public class Sample
{
    public virtual int x { get; set; }
    public virtual string y { get; set; }
}
public class SampleA : Sample
{
}
public class SampleB : Sample
{    
    [Decorated]
    public override string y { get; set; }
}