2

最近我发现自己依赖于自定义 [Attributes] 分配。我正在寻求创建我最常使用的 VCL 控件的基于 RTTI 和泛型的变体;我的目的是将样板代码的数量减少到最低限度,我发现 RTTI、匿名方法和属性非常棒

我有一个不寻常的问题。由于我最终使用了很多 [Attributes],因此我需要一种可读的方式来格式化此代码。可能听起来像一个微不足道的问题,但我对我的格式和缩进非常着迷。属性的问题在于它们没有被 IDE 以特殊方式格式化。在多个字段声明的块中,与 [Attribute] 声明相互交织,您很难猜测什么是类型,什么是属性,什么属性适用于哪个字段。这是一个最小的例子:

type
  [OneAttribute('SomeParam', 7), AnOtherAttribute]
  TSomething = class
  public
    [OneAttribute('SomeParam', 7), AnOtherAttribute]
    FieldName: string;
    [OneAttribute('SomeParam', 7), AnOtherAttribute]
    OtherField: Integer;
    [OneAttribute('SomeParam', 7), AnOtherAttribute]
    function Sum(a,b:Integer):Currency;
    [OneAttribute('SomeParam', 7), AnOtherAttribute]
    property Name:string read FieldName write FieldName;
  end;

我在上面的示例中形成这些 [Attributes] 的方式是代码中最常见的方式C#;不幸的是,除了我自己的,我没有看到使用属性的 Delphi 代码示例。这会稍微好一些,C#因为您不太可能将属性应用于实际字段,而更有可能将它们应用于propertiesor functions; 由于在C#函数实现中紧跟其声明(属性相同),因此您不会得到与 Delphi 相同类型的块;函数和属性声明自然是分开的,因此浏览代码不会因使用属性而受到阻碍。

我尝试了与 delphi 相关的“样式”信息的明显来源。Delphi 2010 中的代码格式化程序根本不理解属性声明!在上面的示例中,如果我删除public关键字并运行内置代码格式化程序,则属性声明的第一行将在class关键字后面移动一行,就好像它声明了一个祖先类一样。

我在 Delphi 2010 源代码周围摸索。要么我的 grep-fu 让我很失望,要么在整个 Delphi 2010 源代码中完全没有使用属性。为了清楚起见,在尝试对属性的实际使用进行 grep 之后(很难,因为使用了方括号分配并且它们很少意味着它是一个属性声明)我开始 grepping TCustomAttribute:没有TCustomAttribute任何地方的后代,所以显然没有使用属性.

最后到问题:

您如何格式化 [Attributes] 以提高可读性?

我的最新解决方案如下所示:

type
 [OneAttribute('SomeParam', 7), AnOtherAttribute]
  TSomething = class
  public
   [OneAttribute('SomeParam', 7), AnOtherAttribute]
    FieldName: string;
   [OneAttribute('SomeParam', 7), AnOtherAttribute]
    OtherField: Integer;
   [OneAttribute('SomeParam', 7), AnOtherAttribute]
    function Sum(a,b:Integer):Currency;
   [OneAttribute('SomeParam', 7), AnOtherAttribute]
    property Name:string read FieldName write FieldName;
  end;

我通常使用两列缩进;对于属性,我正在考虑将属性声明向左移动;因为我的类型、字段、方法和属性总是有至少 2 列右缩进(用于类型)或 4 列用于类成员,所以总是有空间。左缩进似乎与不使用属性的现有声明很好地融合在一起,我希望属性“脱颖而出”,所以左缩进比右缩进更好。

你怎么看?你有更好的想法吗?

4

1 回答 1

7

根据要求回答。

我使用第一个版本,并在每个版本之后添加空行。并且在一组用于“功能分离”的属性/方法-属性对之后可选的两个空行。我还知道重复可见性说明符以分隔方法/属性的功能组。

它需要更多的屏幕空间,但它有帮助..

type
  [OneAttribute('SomeParam', 7), AnOtherAttribute]
  TSomething = class
  public
    [OneAttribute('SomeParam', 7), AnOtherAttribute]
    FieldName: string;

    [OneAttribute('SomeParam', 7), AnOtherAttribute]
    OtherField: Integer;

    [OneAttribute('SomeParam', 7), AnOtherAttribute]
    function Sum(a,b:Integer):Currency;

    [OneAttribute('SomeParam', 7), AnOtherAttribute]
    property Name:string read FieldName write FieldName;

  public
    [OneAttribute('SomeParam', 7), AnOtherAttribute]
    TableName: string;

    [OneAttribute('SomeParam', 7), AnOtherAttribute]
    OtherTable: Integer;

    [OneAttribute('SomeParam', 7), AnOtherAttribute]
    function TableSum(a,b:Integer):Currency;
  end;
于 2013-01-31T08:33:02.507 回答