使用泛型创建可重用方法

本文关键字:方法 创建 泛型 | 更新日期: 2023-09-27 18:22:25

我不确定问题的标题,但这里是:-

我的代码是:-

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;
    }
}

现在,如果我需要对另一个类(比如DogCat )执行同样的操作,这非常好

我正在做的是:-

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