【发布时间】:2011-01-11 00:17:14
【问题描述】:
我是泛型新手,需要一些帮助来构建类和实现方法。
我正在尝试使用泛型序列化 any TObject-JSON。此外,我希望能够重用代码。
这些是我的问题:
如何创建泛型构造函数?我希望能够使用
Self或Default(T),但它只返回nil。V := Marshal.Marshal(ReturnObject)- 这个方法需要TObject,但是我不知道如何引用当前传入的对象。如何在方法中使用它?看看下面截取的代码,标有“问题 3”。
这是我的代码:
TFileOperationResult = class(TObject)
private
FSuccess: Boolean;
//Error: PException;
FLastError: Integer;
function GetFailure: Boolean;
property Failure: Boolean read GetFailure;
public
property Success: Boolean read FSuccess write FSuccess;
property LastError: Integer read FLastError write FLastError;
end;
TResponseObject<T: class> = class(TObject)
private
FReturnObject: T;
function GetReturnObject: T;
function BaseStringsConverter(Data: TObject): TListOfStrings;
public
constructor Create; overload;
property ReturnObject: T read GetReturnObject;
procedure Serialize;
end;
constructor TResponseObject<T>.Create;
begin
// Question 1 - What should go in here?
end;
function TResponseObject<T>.GetReturnObject: T;
begin
Result := Default(T);// Is this correct?
end;
procedure TResponseObject<T>.Serialize;
var
Marshal: TJSONMarshal;
V: TJSONValue;
begin
Marshal := TJSONMarshal.Create(TJSONConverter.Create);
Marshal.RegisterConverter(TResponseObject<T>, BaseStringsConverter);
V := Marshal.Marshal(ReturnObject); // Question 2 - How Can I refer to 'Self'?
OutPut := V.ToString;
Marshal.Free;
end;
调用代码:
procedure TForm1.Test;
var
FileOperationResult: TResponseObject<TFileOperationResult>;
begin
FileOperationResult := TResponseObject<TFileOperationResult>.Create;
FileOperationResult.Serialize;
end;
问题 3:
procedure TForm1.MoveCopyFile<THowNowResponse>(ASource, DDestination: String);
var
FileOperationResult: TFileOperationResult;
begin
FileOperationResult := TFileOperationResult.Create;
// What to do?
end;
非常感谢任何其他 cmets。
【问题讨论】:
-
真的很难知道你想要什么......我认为最好单独写一个问题,因为你似乎有不同的问题,并试图在这里解决所有问题。对于泛型部分... JSON Marshaler 能够编组任何类,所以我不确定您是否要创建一个泛型类以将其用作包装器来编组任何对象,只需使用默认 TJsonConverter 或什么(也许TResponseObject 类名让我不清楚)。
标签: delphi generics delphi-2010