2011-01-11 108 views
2

我新的仿製藥,並需要一些幫助,以結構類和實現方法 - 德爾福2010結構德爾福泛型

我想使用泛型系列化任何TObject的JSON ...我想成爲能夠重用代碼。

我的問題如下:

  1. 如何創建一個泛型構造函數?我希望能夠使用Self或Default(T),但它只返回nil。

  2. 五:= Marshal.Marshal(返回object)...這種方法需要一個TObject的,但我不知道如何引用中傳遞了當前對象

  3. 另外,我該如何使用。這裏面的方法 - 見下面Q3

  4. 任何其他意見非常讚賞。

/////////////////////// ////////////////////

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; 
+0

真的很難知道你想要什麼......我認爲如果你寫出不同的問題會更好,因爲你似乎有不同的問題,並試圖在這裏解決它們。對於泛型部分... JSON Marshaler能夠編組任何類,所以我不確定是否要創建一個泛型類來使用它作爲封裝來封送任何僅使用默認TJsonConverter的對象,或者什麼(可能TResponseObject類的名稱使我不清楚)。 – jachguate 2011-01-11 17:44:05

回答

1

這是很難準確地告訴你在這裏做什麼,但我可以猜測。對於TResponseObject,您需要一個可以包含另一個對象並對其進行操作的對象。在這種情況下,你可能想將它傳遞到構造函數,像這樣:

constructor TResponseObject<T>.Create(value: T); 
begin 
    FReturnObject := value; 
end; 

同樣,如果你犯了一個GetReturnObject方法,它可能應該返回FReturnObject字段的值。 (或者你可以讓訪問屬性的只是直接引用FReturnObject。)

function TResponseObject<T>.GetReturnObject: T; 
begin 
    Result := FReturnObject; 
end; 

這真的很難回答#3,因爲我不知道你想這個做什麼,但希望我的前兩個答案能幫助你回到正軌。請記住,泛型不必混淆。他們基本上只是類型替換。無論您在任何非通用例程中使用正常類型,都可以用<T>替換它以創建通用例程,然後替換適合該特定T的約束條件的任何類型。

+0

嗨梅森,是否可以通過MSN或Google Talk與您聯繫? – 2011-01-11 00:54:23