【问题标题】:Class field (static field) in DelphiDelphi中的类字段(静态字段)
【发布时间】:2013-08-09 11:00:51
【问题描述】:

有一个 TPerson 类。众所周知,FSecondName 对每个对象都是唯一的。

type
  TPerson = class(TObject)
  private
    FAge:        Integer;
    FFirstName:  String;
    FSecondName: String;
  public
    property Age:        Integer read FAge;
    property FirstName:  String  read FFirstName;
    property SecondName: String  read FSecondName;
    constructor Create;
  end;

如何添加类字段(如 C# 中的静态字段) Persons: TDictionary (String, TPerson),其中键是 SecondName,值是类 TPerson 的对象。

谢谢!

【问题讨论】:

  • 没有两个人会有相同的第二个名字?一个狂野、进步的社会,姓氏被 GUID 取代?

标签: delphi static tdictionary


【解决方案1】:

你可以声明一个类变量:

type 
  TMyClass = class
  private
    class var
      FMyClassVar: Integer;
   end;

显然你可以为类变量使用任何你喜欢的类型。

类变量具有全局存储。所以只有一个变量实例。 Delphi 类变量直接类似于 C# 静态字段。

【讨论】:

  • 如何设置值?你能在那个单元的初始化块中做到这一点吗?你需要public class procedure SetMyClassVar 才能让它工作吗?
  • 初始化块有效。和类构造函数一样。在文档中查找。不同于普通的构造函数。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-06-21
  • 1970-01-01
相关资源
最近更新 更多