2012-05-03 11 views
3

私はRESTFULクライアントライブラリを作成していますが、戻りオブジェクト型の一部は要求のパラメータによって異なります。例えばc#子クラスへの型の受け渡し

、クライアントは次のようになりレスポンスオブジェクトを返すExecuteCommandというメソッドを、持っている:ここで

public class MyResponse 
{ 
    public MyResult Result{ get; set; } 
    public MyResponseHeader ResponseHeader { get; set; } 
} 

はMyResultクラスです:

public class MyResult 
{ 
    public object[] DocumentList{ get; set; } 
    public int NumRecords{ get; set; } 
    public int Start{ get; set; } 
} 

私が好きな何か"Document Type"をExecuteCommandメソッドに渡し、渡された型のIDocumentを持つMyResultオブジェクトを持つMyResponseオブジェクトを返します。


MyResponse response = MyClient.ExecuteCommand<MyDocument>(request);

この例では、返されたいのは、MyDocument型のDocumentListを持つMyResultです。

ありがとうございます。

答えて

5
あなたは、あなたのクラスにジェネリックを使用することができ

:次に、あなたが使用してExecuteCommand作成し、あなたのMyResponseを持つことができ

public class MyResponse<T> 
{ 
    public MyResult<T> Result{ get; set; } 
    public MyResponseHeader ResponseHeader { get; set; } 
} 

public class MyResult<T> 
{ 
    public T[] DocumentList{ get; set; } 
    public int NumRecords{ get; set; } 
    public int Start{ get; set; } 
} 

独自のT(この場合はMyDocumentで)、およびVARを使用すると、それがさらに簡単に、より読みやすくなります:

var response = MyClient.ExecuteCommand<MyDocument>(request); 
+0

これは実際に私がそれをどのようにコード化したか、私はちょうどラインの下にタイプを渡すことについて確信がありませんでした。ありがとう、ドリュー – dhysong

関連する問題