'Generic parameter with predefined method signature
I have a HTTP client helper to make post request to an API:
public static T post(U request, string URL)
{
HttpClient httpClient = new HttpClient();
var responseContent = httpClient.PostAsync(
URL,
new StringContent(
JsonSerializer.Serialize<U>(
request,
Config.QrAuthJsonConfig.options
),
System.Text.Encoding.UTF8,
"Application/Json"
)
).Result;
var response = responseContent.Content.ReadAsStringAsync().Result;
return JsonSerializer.Deserialize<T>(response);
}
As you can note, URL is a second param. I would like a way U request can have a method signature to get the URL value from U request instance.
For example:
request.getUrl();
Thank you.
Solution 1:[1]
The (“post”) method with a “generic parameter with a predefined method” could use an interface or a (base) class.
1. Using an interface:
public static TSerialization Post<TSerialization, TRequest>(TRequest request) where TRequest : IUrlInfo
{
//…
}
Define an interface
public interface IUrlInfo
{
string Url { get; set; }
}
that you implement for each request
public class SomeRequest : IUrlInfo
{
public string Url { get; set; } = “default-value-is-not-needed.com”;
// other properties
}
2. Using an abstract class:
public static TSerialization Post<TSerialization, TRequest>(TRequest request) where TRequest : RequestBase
{
//…
}
Define an abstract class
public abstract class RequestBase
{
public string Url { get; set; }
}
that you implement for each request
public class SomeRequest : RequestBase
{
// other properties
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
