要使用C#的RestSharp库增强可读性,您可以遵循以下几点建议:
var request = new RestRequest("users/{id}", Method.GET);
request.AddParameter("id", userId, ParameterType.UrlSegment);
const string BASE_URL = "https://api.example.com";
const string USER_ID_PARAMETER = "id";
public async Task<User> GetUserAsync(int userId)
{
var request = new RestRequest($"{BASE_URL}/users/{userId}", Method.GET);
var response = await client.ExecuteAsync<User>(request);
return response.Data;
}
public async Task<User> GetUserAsync(int userId)
{
try
{
var request = new RestRequest($"{BASE_URL}/users/{userId}", Method.GET);
var response = await client.ExecuteAsync<User>(request);
return response.Data;
}
catch (RequestException ex)
{
// Handle the exception, e.g., log it or throw a custom exception
throw new ApplicationException($"Error fetching user with ID {userId}: {ex.Message}", ex);
}
}
namespace MyApp.Services
{
public class UserService
{
private readonly RestClient _client;
public UserService(RestClient client)
{
_client = client;
}
// RestSharp requests and other methods go here
}
}
public static class RestRequestExtensions
{
public static RestRequest AddUserParameter(this RestRequest request, int userId)
{
request.AddParameter("id", userId, ParameterType.UrlSegment);
return request;
}
}
遵循这些建议,您将能够使用RestSharp库编写更易于阅读和维护的C#代码。