我们可以使这个方法通用吗?

时间:2014-04-10 22:27:05

标签: c# json generics xamarin

我在sample from Xamarin中看到了这个方法,使用JSON访问REST服务器:

List<Country> countries = new List<Country>();
    public Task<List<Country>> GetCountries()
    {
        return Task.Factory.StartNew (() => {
            try {

                if(countries.Count > 0)
                    return countries;

                var request = CreateRequest ("Countries");
                string response = ReadResponseText (request);
                countries = Newtonsoft.Json.JsonConvert.DeserializeObject<List<Country>> (response);
                return countries;
            } catch (Exception ex) {
                Console.WriteLine (ex);
                return new List<Country> ();
            }
        });
    }

其中&#34; CreateRequest&#34;和#34; ReadResponseText&#34;是与REST服务器交互的方法,基本上接收要反序列化并在列表中返回的国家列表。 所以现在,我试图使这个方法通用,以便接收类型并返回指定类型的对象的通用列表,如下所示:

public static Task<List<Object>> getListOfAnyObject(string requested_object, Type type) 
    {
        return Task.Factory.StartNew (() => {
            try {
                var request = CreateRequest (requested_object);
                string response = ReadResponseText (request);
                List<Object> objects = // create a generic list based on the specified type
                objects = Newtonsoft.Json.JsonConvert.DeserializeObject<List<Object>> (response); // not sure how to handle this line
                return objects;
            } catch (Exception ex) {
                Console.WriteLine (ex);
                return ex.Message;
            }
        });
    }

所以我的问题是,如何创建上面的方法以便更多地使用它(将列表转换为我想要的类型)?

List<Country> countries = (List<Country>)(List<?>) getListOfAnyObject("countries",Country.type);

非常感谢提前!

1 个答案:

答案 0 :(得分:2)

尝试这样的事情......

public static Task<List<T>> getListOfAnyObject<T>(string requested_object) 
{
   return Task.Factory.StartNew (() => {
       try {
           var request = CreateRequest (requested_object);
           string response = ReadResponseText (request);
           return Newtonsoft.Json.JsonConvert.DeserializeObject<List<T>> (response); // not sure how to handle this line
       } catch (Exception ex) {
           Console.WriteLine (ex);
           return ex.Message;
       }
   });
}

这样称呼..

List<Country> countries = getListOfAnyObject<Country>("countries");