2013-07-16 44 views
5

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.

Trả lời

5

Định nghĩa phương thức của bạn thiếu thông số loại chung. Ngoài ra, bạn không cần tham số đầu tiên (input), bởi vì bạn không sử dụng nó. Chữ ký của phương pháp của bạn sẽ giống như thế này:

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

Cách sử dụng sẽ là như thế này:

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

Việc thực hiện sẽ sử dụng ở khắp mọi nơi T phương pháp gốc được sử dụng Dog hoặc Animal.

Ngoài ra:
Khối catch của bạn không thêm bất kỳ giá trị nào. Trong thực tế, nó loại bỏ nó bằng cách ném lớp ngoại lệ cơ sở mà bạn không bao giờ nên ném và bằng cách loại bỏ dấu vết ngăn xếp ban đầu. Chỉ cần loại bỏ nó.

Phương pháp cuối cùng sẽ trông như thế này:

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); 
    } 
} 
+1

: - 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

0

Bạn bỏ lỡ nét chung

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

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

tham số của bạn input là vô ích để bạn có thể loại bỏ nó.

Bạn cũng có thể thêm một type costraint:

private T GetAPIData<T>(string parameters, string methodToInvoke) where T:IAnimal 
Các vấn đề liên quan