简体   繁体   English

记录助手和课堂方法

[英]Record Helper & Class Methods

TTransactionType = (ttNone, ttCash, ttCheck, ttDebit);

TTransactionTypeHelper = record helper for TTransactionType
public
  class function ToTransactionType(TranTypeDescription : string) : TTransactionType;
  function ToString(): string;
end;

function TTransactionTypeHelper.ToString: string;
begin
  case Self of
    ttCash:
      Result := 'Cash';
    ttCheck:
      Result := 'Check';
    ttDebit:
      Result := 'Debit'
  else
    Result := '';
  end;
end;

class function TTransactionTypeHelper.ToTransactionType(
  TranTypeDescription: string): TTransactionType;
begin
  if (TranTypeDescription = 'Cash') then
    Result := ttCash
  else if (TranTypeDescription = 'Check') then
    Result := ttCheck
  else if (TranTypeDescription = 'Debit') then
    Result := ttDebit
  else
    Result := ttNone;
end;

The class method, ToTransactionType is accessible via TTransactionTypeHelper (expected). 可通过TTransactionTypeHelper(预期)访问类方法ToTransactionType。

Is there a way to make method ToTransactionType accessible via the enumeration directly? 有没有办法使方法ToTransactionType可以通过枚举直接访问? eg, 例如,

TTransactionType.ToTransactionType('Cash'); 

As @Victoria mentions in a comment, adding static to the ToTransactionType method, will make the call TTransactionType.ToTransactionType('Cash') work just fine. 正如@Victoria在评论中提到的,将静态添加到ToTransactionType方法将使调用TTransactionType.ToTransactionType('Cash')正常工作。

If you want to extend the enumeration type without writing a helper, that is not possible. 如果要扩展枚举类型而不编写帮助程序,则不可能。 But there is another way: 但是还有另一种方法:

Using RTTI and unit TypInfo.Pas you could call GetEnumValue() : 使用RTTI和单位TypInfo.Pas您可以调用GetEnumValue()

var
  i : Integer;
  myTransactionValue : TTransactionType;
begin
  i := GetEnumValue(TypeInfo(TTransactionType),'ttCheck');
  if (i <> -1) then myTransactionValue := TTransactionType(i);
end;

There is also GetEnumName() : 还有GetEnumName()

s := GetEnumName(TypeInfo(TTransactionType),Ord(TTransactionType.ttCheck));  // s = 'ttCheck'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM