gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 22:38:36 25 4
gpt4 key购买 nike

我有这段代码可以获取 Star Wars 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

上面的代码抛出

"Non-static method requires a target."

哪里SWAPIEntity:

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

SWAPIEntity:

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

星球:

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

public string climate { get; set; }
}

我用

来调用它
await StarWarsApi.Get<Planet>();

如何根据我尝试获取的 SWAPIEntity 类型获取 rootUrl 的值?

最佳答案

错误说明了一切。

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

关于c# - 如何根据通用类型返回字符串值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53638582/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com