我使用Delphi 10.3。我有兩種將列舉型別轉換為字串的方法實作。這不是真正的實作,只是服務的本質的兩個變體:
情況1:
在我看來,這是最重要的。
情況1:
TMyClass = class。
private[/span
ctx : TRTTIContext;
public
function asString<T>( const value_ : T ) : string;
function fromString<T>( const value_ : string ) : T。
end。
function TMyClass. asString<T>( const value_ : T ) : string。
var
rttiType : TRTTIType。
begin[/span
rttiType := ctx.getType( typeInfo( T ) ) 。
if ( rttiType.typeKind = tkEnumeration ) then
開始[/span
result := TRTTIEnumerationType( rttiType ).getName( value_ ) 。
end;
end;
function TMyClass. fromString<T>( const value_ : string ) : T。
var
rttiType : TRTTIType。
begin
rttiType := ctx.getType( typeInfo( T ) ) 。
if ( rttiType.typeKind = tkEnumeration ) then
開始[/span
result := TRTTIEnumerationType( rttiType ).getValue( value_ ) 。
end;
end;
案例2:
IMyInterface<T> = interface
['{C03754B7-2225-4EB5-97C1-9820B3D1EBAD}']
function asString( constvalue_ : T ) : string;
function fromString( constvalue_ : string ) : T。
end。
TMyInterfaceImpl<T> = class ( TInterfacedObject, IMyInterface< T> )
private[/span
ctx : TRTTIContext。
public[/span
function asString( constvalue_ : T ) : string;
function fromString( constvalue_ : string ) : T。
end。
function TMyInterfaceImpl<T> 。 asString( const value_ : T ) :string。
var
rttiType : TRTTIType。
begin[/span
rttiType := ctx.getType( typeInfo( T ) ) 。
if ( rttiType.typeKind = tkEnumeration ) then
開始[/span
result := TRTTIEnumerationType( rttiType ).getName( value_ ) 。
end;
end;
function TMyInterfaceImpl<T> 。 fromString( const value_ : string ) : T。
var
rttiType : TRTTIType。
begin
rttiType := ctx.getType( typeInfo( T ) ) 。
if ( rttiType.typeKind = tkEnumeration ) then
開始[/span
result := TRTTIEnumerationType( rttiType ).getValue( value_ ) 。
end;
end;
TRTTIEnumeration.GetName/GetValue在TMyClass實作中作業正常,但在TMyInterfaceImpl<T>中卻無法編譯:
E2010不兼容的型別:'System.Rtti.T'和'MyInterfaceImpl.T'
E2531方法'GetValue'需要明確的型別引數
但是我想把這個服務作為一個介面來實作。有什么辦法可以用TMyInterfaceImpl<T>來實作嗎?通用型別的引數化方法在介面中是不允許的。(procedure foo<T>( const value_ : T );)
uj5u.com熱心網友回復:
GetName和GetValue類函式在TRTTIEnumerationType中是引數化函式:
class function GetName< T{: enum}>(AValue: T): string; reintroduce; static;
class function GetValue<T{: enum}>(const AName: string): T; static;
當你呼叫它們時,你需要添加T GetName<T>(...) 和 GetValue<T>(...)
function TMyInterfaceImpl<T> 。 asString( const value_ : T ) :string。
var
rttiType : TRTTIType。
begin[/span
rttiType := ctx.getType( typeInfo( T ) ) 。
if ( rttiType.typeKind = tkEnumeration ) then
開始[/span
result := TRTTIEnumerationType( rttiType ).getName<T>( value_ ) 。
end。
end。
function TMyInterfaceImpl<T> 。 fromString( const value_ : string ) : T。
var
rttiType : TRTTIType。
begin
rttiType := ctx.getType( typeInfo( T ) ) 。
if ( rttiType.typeKind = tkEnumeration ) then
開始[/span
result := TRTTIEnumerationType( rttiType ).getValue<T>( value_ ) 。
end。
end。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/316490.html
標籤:
