簡體   English   中英

使用泛型創建可重用方法

[英]Creating Reusable Method using generics

我不確定問題的標題,但是這里是:

我的代碼為:-

HttpClient client = new HttpClient();// Create a HttpClient
client.BaseAddress = new Uri("http://localhost:8081/api/Animals");//Set the Base Address

//eg:- methodToInvoke='GetAmimals'
//e.g:- input='Animal' class
HttpResponseMessage response = client.GetAsync('GetAllAnimals').Result;  // Blocking call!

if (response.IsSuccessStatusCode)
{
    XmlSerializer serializer = new XmlSerializer(typeof(Animal));//Animal is my Class (e.g)
    string data = response.Content.ReadAsStringAsync().Result;
    using (MemoryStream ms = new MemoryStream(UTF8Encoding.UTF8.GetBytes(data)))
    {
        var _response = (Animal)serializer.Deserialize(ms);
        return _response;
    }

}

現在,如果我需要在另一堂課(例如“ Dog或“ Cat做同樣的事情,這將非常有效

我正在做的是:

HttpClient client = new HttpClient();// Create a HttpClient
    client.BaseAddress = new Uri("http://localhost:8081/api/Animals");//Set the Base Address

    //eg:- methodToInvoke='GetAmimals'
    //e.g:- input='Animal' class
    HttpResponseMessage response = client.GetAsync('GetAllDogs').Result;  // Blocking call!

    if (response.IsSuccessStatusCode)
    {
        XmlSerializer serializer = new XmlSerializer(typeof(Dog));//Animal is my Class (e.g)
        string data = response.Content.ReadAsStringAsync().Result;
        using (MemoryStream ms = new MemoryStream(UTF8Encoding.UTF8.GetBytes(data)))
        {
            var _response = (Dog)serializer.Deserialize(ms);
            return _response;
        }

    }

現在,我希望它將其更改為Generic類,如下所示:-

private T GetAPIData(T input,string parameters, string methodToInvoke)
        {
            try
            {

                HttpClient client = new HttpClient();
                client.BaseAddress = new Uri("http://localhost:8081/api/Animals");

                //eg:- methodToInvoke='GetAmimals'
                //e.g:- input='Animal' class
                HttpResponseMessage response = client.GetAsync(methodToInvoke).Result;  // Blocking call!

                if (response.IsSuccessStatusCode)
                {
                    XmlSerializer serializer = new XmlSerializer(typeof(input));
                    string data = response.Content.ReadAsStringAsync().Result;
                    using (MemoryStream ms = new MemoryStream(UTF8Encoding.UTF8.GetBytes(data)))
                    {
                        var _response = (input)serializer.Deserialize(ms);
                        return _response;
                    }

                }
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
            return (T)input;
        }

但是,我無法做到。 我什至不知道如何稱呼這種方法?

var testData = GetAPIData(new Aminal(),null,'GetAmimals');

這會工作嗎?這是我第一次使用泛型。

您的方法的定義缺少通用類型參數。 另外,您不需要第一個參數( input ),因為您沒有使用它。 方法的簽名應如下所示:

private T GetAPIData<T>(string parameters, string methodToInvoke)

用法如下:

var testData = GetAPIData<Animal>(null, "GetAllAnimals");

該實現將在最初使用DogAnimal方法中到處使用T

此外:
您的catch塊沒有任何價值。 實際上,它通過拋出您不應該拋出的基本異常類並丟棄原始堆棧跟蹤來將其刪除。 只需將其刪除。

最終方法如下所示:

private T GetAPIData<T>(string parameters, string methodToInvoke)
{
    HttpClient client = new HttpClient();
    client.BaseAddress = new Uri("http://localhost:8081/api/Animals");

    //eg:- methodToInvoke='GetAmimals'
    //e.g:- input='Animal' class
    HttpResponseMessage response = client.GetAsync(methodToInvoke).Result;

    if (!response.IsSuccessStatusCode)
        throw new InvalidOperationException("Request was not successful");

    XmlSerializer serializer = new XmlSerializer(typeof(T));
    string data = response.Content.ReadAsStringAsync().Result;
    using (MemoryStream ms = new MemoryStream(UTF8Encoding.UTF8.GetBytes(data)))
    {
        return (T)serializer.Deserialize(ms);
    }
}

您錯過了通用定義

private T GetAPIData<T>(string parameters, string methodToInvoke)

var testData = GetAPIData<Animal>(null,'GetAmimals');

您的參數input無用,因此可以將其刪除。

您也可以添加costraint類型

private T GetAPIData<T>(string parameters, string methodToInvoke) where T:IAnimal

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM