如何根据通用类型返回字符串值

时间:2018-12-05 18:28:30

标签: c# generics

我有以下代码来获取《星球大战》 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

上面的代码抛出

  

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

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类型?

1 个答案:

答案 0 :(得分:3)

错误说明了一切。

您正在尝试调用非静态成员,因此您需要传递一个实例。我想对您来说,简单的解决方案是使该属性为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; }
}
相关问题