2017-06-22 220 views
0

我想创建一个方法,将调用基于HttpMethod的其他方法。 我的方法是这样的: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); 
    } 
} 

的问题是,开关呻吟一下:

一个恒定值,预计

而且每一种情况下用红色下划线。 有谁知道我在做什么错?

+1

'HttpMethod.Post'和所有其他不是常量,这是switch语句所期望的。如果你检查[源代码](例如https://github.com/dotnet/corefx/blob/master/src/System.Net.Http/src/System/Net/Http/HttpMethod.cs),你会看到为什么。您可以使用战略模式来解决这个问题。 – Nkosi

回答

2

因为它已经指出的问题是,HttpMethodDeletePost ...等。属性是实例而不是常量或枚举。还有人指出,它们是可以平等的。

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

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); 
    } 
} 
1

由于HttpMethod静态属性,如HttpMethod.PutHttpMethod.Post,是HttpMethod类的实例,你不能在switch语句中使用他们作为CASE表达式,就好像它们是一个enum的成员。

这些对象是equatable,不过,这样你就可以在IF-THEN-ELSE链使用它们,或者在Dictionary<HttpMethod,SomeDelegate>其中SomeDelegate是代表任务的动作类型,你想运行:

if (method == HttpMethod.Post) { 
    return await PostAsync(client, url, data); 
} else if (method == HttpMethod.Put) { 
    return await PutAsync(client, url, data); 
} else if (method == HttpMethod.Delete) { 
    return await DeleteAsync(client, url, parameters); 
} else { 
    return await GetAsync(client, url, parameters); 
} 
1

你不能像dasblinkenlight那样做,而Nkosi说。最简单的解决方法是使用HttpMethod.Method和case语句的硬编码字符串。

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