2

之间的语义区别是什么:

RttiType.TypeKind 和 RttiType.Name ?

我问是因为原则上不能从名称中推断出 TypeKind 吗?

4

2 回答 2

3

TypeKind和的Name属性TRttiType是完全不同的东西。

  • TypeKind告诉你你有什么样的类型。这可以是TTypeKind枚举类型中定义的 23 个不同选项之一。
  • Name告诉你你有哪种类型。这是一个字符串,有无限数量的可能值。

不同的类型(通常)会有不同的名称,但可能有相同的TypeKind. 例如考虑这个简单的演示。

program RttiDemo;

{$APPTYPE CONSOLE}

uses
  Rtti;

procedure Main;
var
  Context: TRttiContext;
  TObjectType, TInterfacedObjectType: TRttiType;
begin
  TObjectType := Context.GetType(TObject);
  TInterfacedObjectType := Context.GetType(TInterfacedObject);
  Writeln(TObjectType.Name);
  Writeln(TInterfacedObjectType.Name);
  Assert(TObjectType.TypeKind=TInterfacedObjectType.TypeKind);
end;

begin
  Main;
  Readln;
end.

输出是:

对象
接口对象

因此,您不能从类型名称推断类型种类,因为种类和名称是完全不同的东西。

于 2013-06-04T09:59:06.283 回答
2

RTTIType.Name是一个字符串。RTTI.TypeKind是适合在循环或case语句中使用的枚举类型。它们根本不一样,“从字符串推断”在实际使用时根本不是一回事。写起来更清晰、简洁、高效

case TypeKind of
  tkInteger, tkInt64: DoSomething;
  tkEnumeration: DoThisInstead;
...

比写

if (Name = 'tkInteger') or (Name = 'tkInt64') then
  DoSomething
else if (Name = 'tkEnumeration') then
  DoThisInstead
...
于 2013-06-03T23:38:24.117 回答