如何使用字符串索引的属性?

时间:2017-02-21 13:41:52

标签: delphi delphi-7

我有这段代码:

type
  TMyClass = class
    private
      procedure SetKeyValue(const Key: WideString; Value: Widestring);
      function GetKeyValue(const Key: WideString): WideString;
    public
      // this works
      property KeyValue[const Index: WideString] : WideString read GetKeyValue write SetKeyValue;

      // this does not compile
      // [Error]: Incompatible types: 'String' and 'Integer'
      property Speed: WideString index 'SPEED' read GetKeyValue write SetKeyValue;
  end;

Speed属性给出了错误:

  

不兼容的类型:'String'和'Integer'

我需要索引为字符串。 是否可以将index与字符串值一起使用?

3 个答案:

答案 0 :(得分:6)

这是不可能的。索引属性仅支持Integer作为索引常量。

参见documentation(自己的重点):

  

索引说明符允许多个属性在表示不同值时共享相同的访问方法。索引说明符由指令index后跟-21474836472147483647 之间的整数常量组成。如果属性具有索引说明符,则其readwrite说明符必须列出方法而不是字段。

答案 1 :(得分:2)

使用index说明符是不可能的,因为它只支持整数索引。您将不得不使用一组单独的属性getter / setter方法:

type
  TMyClass = class
  private
    ...
    procedure SetSpeed(const Value: WideString);
    function GetSpeed: WideString;
  public
    ...
    property Speed: WideString read GetSpeed write SetSpeed;
  end;

procedure TMyClass.SetSpeed(const Value: WideString);
begin
  KeyValue['SPEED'] := Value;
end;

function TMyClass.GetSpeed: WideString;
begin
  Result := KeyValue['SPEED'];
end;

答案 2 :(得分:0)

效果很好

属性值[const Name:string]:string read GetValue write SetValue;

{ClassName=class}
private
 fArrayKey: Array of String;{1}
 fArrayValue: Array of String;{2}
 procedure  Add(const Name, Value: string);
 function GetValue(const Name: string): string;
 procedure SetValue(const Name, Value: string);
published
 property Values[const Name: string{1}]: string{2} read GetValue write SetValue;
function   {ClassName.}GetValue(const Name: string): string;
Var I:integer;
Begin
Result := '#empty';
  for I := low(fArrayKey) to high(fArrayKey) do
    if fArrayKey[i]=Name then
       Begin
         Result := fArrayValue[i];
         Break
       End;
If result='#empty' the Raise Exception.CreateFmt('Key %s not found',[name]);
End;
procedure  {ClassName.}SetValue(const Name, Value: string);
var i,j:integer
Begin
j:=-1;
  for I := low(fArrayKey) to high(fArrayKey) do
    if fArrayKey[i]=Name then
       Begin
         j:= i;
         Break
       End;
If j=-1 then Add(name,value) else fArrayValue[i]:= Value;
End;
procedure  {ClassName.}Add(const Name, Value: string);
begin
  SetLength(fArrayKey,Length(fArrayKey)+1);
  SetLength(fArrayValue,Length(fArrayValue)+1);
  fArrayKey  [Length(fArrayKey)  -1] := Name;
  fArrayValue[Length(fArrayValue)-1] := Value;
end;

http://docwiki.embarcadero.com/RADStudio/Tokyo/en/Properties_(Delphi)