我有以下代码来获取《星球大战》 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
类型?
答案 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; }
}