繁体   English   中英

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

[英]How to return string value depending on type of generic

我有这个代码来获取星球大战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依赖于为T传递哪种类型的SWAPIEntity

上面的代码抛出

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

SWAPIEntity

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

SWAPIEntity

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

Planet

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

    public string climate { get; set; }
}

我称之为

await StarWarsApi.Get<Planet>();

我怎样才能获得rootUrl的值,具体取决于我想要获得的SWAPIEntity类型?

错误说明了一切。

您正在尝试调用非静态成员,因此您需要传递实例。 我想你的简单解决方案是使这个属性保持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; }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM