如何找出字符串值是否作为名为TEntity的类型化记录存在



我有一个记录,我命名为TEntity

type
  TEntity = record
    VariableName : string;
    VariableValue : double;
  end;
   Mass : TEntity;
   Force : TEntity;
   Acceleration : TEntity;
    ReturnedValue : string;
   mystring : string;
Mass.VariableName := 'Mass';
Mass.VariableValue := 5;

我也有一个从函数返回的字符串值这个字符串值被放在return值中。

returnedvalue := myfunction(mystring);
//returnedvalue is Mass
//returnedvalue = Mass

现在我有TEntity类型的记录,我如何在运行时动态检查返回到returnedvalue中的单词是否作为TEntity存在。我需要一个模块化的函数,这样不管弦是质量还是加速度,它都能工作。

谢谢,本

如果您想要跟踪所有存在的TEntity,您将不得不将它们添加到某种类型的列表(或注册表)中,并确保在它们从存在中删除时将它们从列表中删除。在此之后,检查字符串是否作为TEntity存在就变得微不足道了:只需通过列表(或注册表)找到它。

虽然类的实例是显式创建的,并且(除非通过接口实现引用计数)显式释放,但将TEntity转换为类而不是记录可能更容易,尽管它确实有一个缺点,即如果不首先创建Mass,就不能再执行Mass.VariableValue := 1

你可能最终不得不走这条路。因为,尽管现在的记录可以有方法(不确定从哪个Delphi版本开始),并且你可以添加一个构造函数来自动将实体注册到列表中,但不幸的是,它们不支持析构函数,所以你不能提供从列表中自动取消注册的功能。

未经测试的代码,在浏览器中编写

type
  TEntity = class(TObject)
  private
    FName: string;
    FValue: Double;
  public
    constructor Create(const aName: string; const aValue: Double);
    destructor Destroy; override;
    property Name: string read FName write FName;
    property Value: Double read FValue write FValue;
  end;
function FindEntity(const aName: string): TEntity;
implementation
var
  _EntityList: TObjectList;
constructor TEntity.Create(const aName: string; const aValue: Double);
begin
  Assert(FindEntity(aName) = nil, 'Entity should not already be in the _EntityList');
  _EntityList.Add(Self);
  FName := aName;
  FValue := aValue;
end;
destructor TEntity.Destroy;
begin
  _EntityList.Extract(Self);
  inherited Destroy;
end;
function FindEntity(const aName: string): TEntity;
begin
  Result := nil;
  for i := 0 to _EntityList.Count - 1 do begin
    if SameText(TEntity(_EntityList[i]).Name, aName) then begin
      Result := TEntity(_EntityList[i]);
      Break;
    end;
  end;
end;
initialization
  _EntityList := TObjectList.Create({aOwnsObjects=}False);
finalization
  FreeAndNil(_EntityList);

当然,当内存中同时有两个以上的实体时,FindEntity函数应该进行优化。优化的第一行将是对名称列表进行排序并保持排序,并使用二进制搜索来查找特定的实体。

您可以从TInterfacedObject派生TEntity,这样您就可以获得引用计数的好处,并且当它们的引用计数下降到零时实例将被自动销毁。如果采用这种方法,仍然需要显式地创建实例。此外,在这种情况下,您应该将_EntityList转换为TInterfaceList,因为这意味着引用计数永远不会降为零(向列表添加实例会使引用计数增加1)…

最新更新