我应该在部分 类 中分离属性和方法吗?

Should I separate properties and methods in partial classes?

我正在为应用程序编写基础 classes,并希望正确构建它们以实现长期可维护性。为此,我正在研究要实现的设计模式、接口的使用、抽象 classes,以及将持久性与 activity 分开。我满脑子都是模式、范式和原则。

我有一个 class Product,我为其创建了一个接口 IProduct。我相信我需要制作 Product 和抽象 class,因为它的任何实例都必须是 属性 Category 的六个值之一。那么,我的第一个问题:以下是合适的方法吗?

abstract class Product : IProduct
{
    // Fields
    // Properties
    // Methods
}

interface IProduct
{
    // Properties
}

public class Model : IProduct
{
    public Model()
    {
        Category = "Model";
    }

    // Model-specific fields
    // Model-specific properties
    // Model-specific methods
}

我阅读的文章,包括之前在这里回答的问题,表明我应该设计分离属性和方法(持久性和 activity)。为此,上面的代码真的应该像这样吗?

abstract class Product : IProduct
{
    // Fields
    // Properties
    // Methods
}

interface IProduct
{
    // Properties
}

public partial class Model : IProduct
{
    public Model()
    {
        Category = "Model";
    }

    // Model-specific fields
    // Model-specific properties
}

public partial class Model : IProduct
{
    // Model-specific methods
}

当然,前提是我的第一部分是正确的,但也许答案会启发我应该如何做事。

最后,如果属性和方法的分离是一件好事,并且 Product 有一些方法适用于它的所有具体版本,我是否应该将它们移到一个单独的抽象中 class像这样?

abstract class Product : IProduct
{
    // Fields
    // Properties
}
abstract class Product : IProduct
{
    // Methods
}

我看到保留 partial classes 的唯一用途是当两个独立的系统更新这两个文件时。例如,当使用 Visual Studio 设计器(例如 Windows 表单设计器)更新他们自己的 class 文件时就是如此。对于您拥有的另一个自动生成的 class,另一件事可能是正确的。一个由系统维护,一个由您维护。

我从未有过自己维护两个单独的 partial class 文件的冲动。我通常使用 #region 指令来拆分方法和属性。

就我个人而言,我更喜欢结合基于语义和基于可见性的方法来对 class 中的成员进行排序。实际上我不知道谁曾经 'invented' 根据语言实体的类型(即组中的字段、组中的属性等)对成员进行排序的规则。这在可读性方面几乎没有任何意义。

最好使用 #region 指令将它们分开。此外,我倾向于使用水平线 (------…---) 来使代码更具可读性。

示例:

public class SomeClass : ParentClass, ISomeInterface
{
    #region ------ Large feature 1 ----------------------------
    … // any non-private members related to 'Large feature 1' go here
    #endregion

    #region ------ Large feature 2 ----------------------------
    … // any non-private members related to 'Large feature 2' go here
    #endregion

    #region ------ Implementation of ISomeInterface -----------
    … // ISomeInterface implementation goes here, comments are *not* repeated
    #endregion

    #region ------ ParentClass overrides ----------------------
    … // parent class members' overrides go here, comments are *not* repeated
    #endregion

    #region ------ Internals ----------------------------------
    … // any private members, i.e. the actual implementation
    #endregion
}

没有理由过度使用部分声明,除非您确实需要将它们放在单独的文件中。一个很好的理由是 class 的一部分是自动生成的。但是,仅仅为了分隔成员而使用部分声明远不如一致使用区域可读性和可维护性。

此外,我不喜欢将 属性 声明和相应的支持字段声明分开(以防您不能使用自动属性)。以下内容更具可维护性和可读性:

public int SomeProperty
{
    get { … return someProperty; }
    set { someProperty = value; … }
}
private int someProperty;