代码之家  ›  专栏  ›  技术社区  ›  Bassie

如何根据泛型的类型返回字符串值

  •  1
  • Bassie  · 技术社区  · 6 年前

    我有以下代码来获取星球大战API对象的列表:

    public static async Task<IList<T>> Get<T>() 
        where T : SWAPIEntity
    {
        var entities = new List<T>();
        var rootUrl = (string)typeof(T).GetProperty("rootUrl").GetValue(null);
    
        var url = $"{baseUrl}/{rootUrl}";
    
        var result = await GetResult<T>(url);
        entities.AddRange(result.results);
    
        while (result.next != null)
        {
            result = await GetResult<T>(result.next);
            entities.AddRange(result.results);
        }
    
        return entities;
    }
    

    我想去哪里 rootUrl 取决于哪种类型的 SWAPIEntity 被传为 T .

    上面的代码抛出

    “非静态方法需要一个目标。”

    虚荣 :

    public class SWAPIEntity 
    {
        public string name { get; }
    }
    

    虚荣

    公营部门
    {
    公共字符串名称{get;}
    

    Planet :

    public class Planet : SWAPIEntity
    {
        public string rootUrl { get; } = "planets";
    
        public string climate { get; set; }
    }
    

    我称之为

    await StarWarsApi.Get<Planet>();
    

    根URL 取决于哪种类型的 虚荣 我在试着得到什么?

    1 回复  |  直到 6 年前
        1
  •  3
  •   Ofir Winegarten    6 年前

    错误说明了一切。

    您正试图调用非静态成员,因此需要传递一个实例。我想对你来说最简单的解决办法就是把这个属性 static

    public class Planet : SWAPIEntity
    {
        public static string rootUrl { get; } = "planets";
        // Or newer simpler syntax:
        // public static string rootUrl => "planets";
        public string climate { get; set; }
    }