3

HttpClient 呼び出しを使用して簡略化するために作成したメソッドがあります。メソッド HttpReponse.Content.ReadAsAsync().Result を使用して、API からの応答を取得します。

これはすべてうまくいきます。私の方法は次のようになります。

    public static T ExecuteAPIGetRequest<T>(string url, Dictionary<string, string> parameters)
    {

        HttpClient client = new HttpClient();
        //basic authentication

        var t = new object();
        string baseURL =  "myurl"; 

        //Execute request
        HttpResponseMessage response = client.GetAsync(baseURL).Result;

        if (response.IsSuccessStatusCode)
        {
            return response.Content.ReadAsAsync<T>().Result;  
        }
        else
        {
            return (T)t;
        }
    }

私の質問は、クエリが失敗した場合、空の型の T を返す必要があるということです。これは、私が作成したカスタム クラスであれば問題ありませんが、string や string[] などのオブジェクトでは機能しません。何か案は?

乾杯

NCBL

4

2 に答える 2

7

戻してみるdefault(T)

if (response.IsSuccessStatusCode)
{
    return response.Content.ReadAsAsync<T>().Result;  
}
else
{
    return default(T);
}

defaultは参照型を返しnull、数値 、 などをゼロintdoubleし、カスタムstructおよびの対応するデフォルト値を返しますenum

Daniel は親切に 1 つの問題を指摘しました。参照型に対してnullではなくデフォルトのオブジェクトを返したい場合は、ジェネリックな constraint を定義する必要があります。パラメーターなしのコンストラクターへの呼び出しを使用して、型のオブジェクトをインスタンス化できるようになりました。完全な方法を以下に示します。new T()T

public static T ExecuteAPIGetRequest<T>(string url, 
                                        Dictionary<string, string> parameters)
                                                                   where T : new()
{

    HttpClient client = new HttpClient();

    //basic authentication

    string baseURL =  "myurl"; 

    HttpResponseMessage response = client.GetAsync(baseURL).Result;

    if (response.IsSuccessStatusCode)
    {
        return response.Content.ReadAsAsync<T>().Result;  
    }
    else
    {
        return new T(); //returns an instance, not null
    }
}

これで、null ではなく、参照型のデフォルト オブジェクトが返されます。オープン型Tは、デフォルトでコンストラクターを持つ型のみを取ることができます (パラメーターなし)。

于 2013-04-02T14:15:00.323 に答える