gpt4 book ai didi

c# - 以 HttpMethod 作为参数的泛型方法

转载 作者:太空狗 更新时间:2023-10-29 19:59:24 26 4
gpt4 key购买 nike

我正在尝试创建一个方法来调用基于 HttpMethod 的其他方法。我的方法如下所示:

public async Task<string> CreateAsync<T>(HttpClient client, string url, HttpMethod method, T data, Dictionary<string, string> parameters = null)
{
switch(method)
{
case HttpMethod.Post:
return await PostAsync(client, url, data);
case HttpMethod.Put:
return await PutAsync(client, url, data);
case HttpMethod.Delete:
return await DeleteAsync(client, url, parameters);
default:
return await GetAsync(client, url, parameters);
}
}

问题是,交换机正在提示这个:

A constant value is expected

每个案例都带有红色下划线。有谁知道我做错了什么?

最佳答案

正如已经指出的那样,问题在于 HttpMethod DeletePost 等。属性是实例而不是常量或枚举。也有人指出它们是等价的。

我唯一想补充的是,如果这是 C# 7,您可以使用模式匹配而不是 if..else if....else if... 链:

public async Task<string> CreateAsync<T>(HttpClient client, string url, HttpMethod method, T data, Dictionary<string, string> parameters = null)
{
switch (method)
{
case HttpMethod m when m == HttpMethod.Post:
return await PostAsync(client, url, data);
case HttpMethod m when m == HttpMethod.Put:
return await PutAsync(client, url, data);
case HttpMethod m when m == HttpMethod.Delete:
return await DeleteAsync(client, url, parameters);
default:
return await GetAsync(client, url, parameters);
}
}

关于c# - 以 HttpMethod 作为参数的泛型方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44703750/

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