使用泛型创建可重用方法

Shu*_*ubh 5 c# 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;
    }

}
Run Code Online (Sandbox Code Playgroud)

这非常有效,现在如果我需要为另一个班级做同样的事情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;
        }

    }
Run Code Online (Sandbox Code Playgroud)

现在,我希望它将它更改为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;
        }
Run Code Online (Sandbox Code Playgroud)

但是,我无法做到.甚至困惑我怎么称呼这种方法?

var testData = GetAPIData(new Aminal(),null,'GetAmimals');
Run Code Online (Sandbox Code Playgroud)

这会有用......这是我第一次使用泛型.

Dan*_*rth 5

您的方法的定义缺少泛型类型参数.此外,您不需要第一个参数(input),因为您不使用它.您的方法的签名应如下所示:

private T GetAPIData<T>(string parameters, string methodToInvoke)
Run Code Online (Sandbox Code Playgroud)

用法如下:

var testData = GetAPIData<Animal>(null, "GetAllAnimals");
Run Code Online (Sandbox Code Playgroud)

该实现将在所使用T的原始方法的任何地方使用DogAnimal.

此外:
您的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);
    }
}
Run Code Online (Sandbox Code Playgroud)