【问题标题】:Can we make this method generic?我们可以使这个方法通用吗?
【发布时间】:2014-04-10 22:27:04
【问题描述】:

我在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> ();
            }
        });
    }

其中“CreateRequest”和“ReadResponseText”是与 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);

非常感谢!

【问题讨论】:

  • 考虑将函数的名称更改为 getAll&lt;Country&gt;("country") ... 根据您的需要,您也可以使用通用存储库模式,因此您只需说 repo.GetAll(); 它知道什么你说的是

标签: c# json generics xamarin


【解决方案1】:

试试这样的..

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");

【讨论】:

  • Newtonsoft 提供了一种用于反序列化的异步方法 (DeserializeObjectAsync&lt;T&gt;)。
  • 嗨!你的方法效果很好,非常感谢!我只是将catch返回调整为这样,否则编译器会抱怨说整个代码没有返回值: (...) } catch (Exception ex) { Console.WriteLine (ex);返回新列表(); } }); }
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-11-19
  • 2011-06-09
  • 1970-01-01
  • 2020-01-13
  • 2020-02-12
  • 2010-11-18
  • 2021-11-10
相关资源
最近更新 更多