gpt4 book ai didi

delphi - 使用 TValue 将字符串转换为枚举类型?

转载 作者:行者123 更新时间:2023-12-03 15:05:55 25 4
gpt4 key购买 nike

我想使用 TValue 将字符串转换为枚举类型,我用谷歌搜索但没有找到如何做到这一点。

type 
TEnumTest = (etFirst, etSecond);

var
D: TEnumTest;
begin
D := StrToENumTest('etFirst');
end;

function StrToEnumTest(pStr:String):TEnumTest;
var
V: TValue;
begin
V := TValue.From<String>(pstr);
Result := V.AsType<TEnumTest>;
end;

这不起作用。那肯定是一些愚蠢的事情,我没有看到 - 但我没有找到了。我做错了什么?

我知道如何使用 GetEnumValue。

编辑:@Warren,它放在这里,因为这样更容易发布代码:

  TEnumUtils = class
class function GetAs<T>(pValor: String): T;
end;

class function TEnumUtils.GetAs<T>(pValor: String): T;
var
Tipo: PTypeInfo;
Temp: Integer;
PTemp: Pointer;

begin
Tipo := TypeInfo(T);
Temp := GetEnumValue(Tipo, pValor);
PTemp := @Temp;
Result := T(PTemp^);
end;

用法:

type 
TEnumTest = (etFirst, etSecond);

var
D: TEnumTest;
begin
D := TEnumUtils.GetAs<TEnumTest>('etFirst');
end;

最佳答案

这是您要找的吗?

Using Generics & RTTI to get enum string name or enum value

Enum conversion with Generics / RTTI Unit System.RTTI is cross platform and contains a great class for converting enum to string and back: TRttiEnumerationType

The TRttiEnumerationType class has two class functions (methods you can call without creating an instance of the class) that clean up the code required from using the TypInfo methods. The easy reading version of these method declarations is:

class function GetName(AValue: T):string; class function GetValue(AName: string): T; Note these methods use Generics (thats the T bit). Generics are very cool as they allow you to write functionality once and then reuse it with different types at different times in code.

In this instance TRttiEnumerationType’s generic methods are for use with Enums only and not other class types as the functionality defined is specific for Enum’s.

To convert the TCompass enum now after adding RTTI to the uses would look like this.

S := TRttiEnumerationType.GetName(D); ShowMessage(S); To convert back from a string is also simpler.

D := TRttiEnumerationType.GetValue(S); How much easier is that to read! and as we have only had to declare the type once, we have less chance of silly copy paste errors in code.

关于delphi - 使用 TValue 将字符串转换为枚举类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2472487/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com