Tôi không chắc chắn về tiêu đề của câu hỏi, nhưng ở đây nó là: -Tạo Reusable Phương pháp sử dụng Generics
Tôi có mã của tôi là: -
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;
}
}
này hoạt động hoàn toàn tốt, bây giờ nếu tôi cần phải làm tương tự cho lớp khác nói Dog
hoặc Cat
những gì tôi đang làm là: -
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;
}
}
Bây giờ, tôi muốn nó thay đổi nó thành một lớp Generic, một cái gì đó như thế này dưới đây: -
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;
}
Nhưng, tôi không thể làm điều đó. Bối rối ngay cả làm thế nào tôi sẽ gọi phương pháp này?
var testData = GetAPIData(new Aminal(),null,'GetAmimals');
Đây có phải là lần đầu tiên tôi làm việc với Generics không.
: - Cảm ơn bạn .. Một tấn triệu ... 1 đề cập đến 'Usage', nó đã đưa ra một bức tranh rõ ràng. – Shubh