创建并调用通用异步方法

cla*_*ent 1 c# generics

我遇到一种情况,我需要在泛型声明中动态确定对象的类型(编译时间很好)。

我有一个这样的方法:

private async Task<T> Post<T>(string path, Request data)
{
    var authPath = GetAuthenticatedPath(path);
    var response = await _client.PostAsJsonAsync<Request>(authPath, data);
    return response;
}
Run Code Online (Sandbox Code Playgroud)

问题是我真的需要它更像这样操作:

private async Task<T> Post<T>(string path, Request data)
{
    var authPath = GetAuthenticatedPath(path);
    var response = await _client.PostAsJsonAsync<data.GetType()>(authPath, data);
    return response;
}
Run Code Online (Sandbox Code Playgroud)

因为我需要它在转换为 JSON 时将数据变量格式化为 ActualRequestType 而不是 Request 类型。问题是您无法在类型声明中执行 data.GetType() 。

dee*_*see 6

将您的签名修改为:

private async Task<T> Post<T, TRequest>(string path, TRequest data)
    where TRequest : Request
{
    var authPath = GetAuthenticatedPath(path);
    var response = await _client.PostAsJsonAsync<TRequest>(authPath, data);
    return response;
}
Run Code Online (Sandbox Code Playgroud)

该条件将确保您仍然收到有效的Request对象,并且实际类型将继续进行PostAsJsonAsync调用。