英文:
C# Generics: Simplifying method declaration by deduplication
问题
Sure, here is the translated content without any additional information:
我正在构建一个请求执行系统,遵循通用的响应样式。当前的实现显得过于冗长,因为我需要两次指定请求体模型(REQ
):
var wrappedRequest = new Request<REQ>(...); // 为了简洁而省略
IRequestExecutionResult<Request<REQ>, REQ> result = await exec.ExecuteAsync<Request<REQ>, REQ>(wrappedRequest);
这是通过接口上的以下方法定义实现的:
ValueTask<IRequestExecutionResult<T, O>> ExecuteAsync<T, O>(T request, CancellationToken cancel = default) where T : IRequest<O>;
我正在针对最新的 .NET(7)版本进行开发。是否有一种方法可以简化通用方法签名,以便我只需指定请求类型,并从中获取请求体类型?
目标:
IRequestExecutionResult<Request<REQ>> result = await exec.ExecuteAsync<Request<REQ>>(wrappedRequest);
Please note that this is a direct translation of the provided content without additional context or information.
英文:
I am building a request execution system that follows a generic response style. The current implementation feels needlessly verbose, in that I specify the request body model (REQ
) twice:
var wrappedRequest = new Request<REQ>(...); // omitted for brevity
IRequestExecutionResult<Request<REQ>, REQ> result = await exec.ExecuteAsync<Request<REQ>, REQ>(wrappedRequest);
This is achieved with the following method definition on an interface:
ValueTask<IRequestExecutionResult<T, O>> ExecuteAsync<T, O>(T request, CancellationToken cancel = default) where T : IRequest<O>;
I am targeting latest .NET (7). Is there a way to simplify the generic method signature so I only need to specify the request type, and pull the body type off that?
Goal:
IRequestExecutionResult<Request<REQ>> result = await exec.ExecuteAsync<Request<REQ>>(wrappedRequest);
答案1
得分: 1
你可以考虑只移除一个泛型层级,并将其写成:
ValueTask<IRequestExecutionResult<T>> ExecuteAsync<T>(IRequest<T> request, CancellationToken cancel = default)
这样有助于类型推断。有时过多使用泛型会导致方法解析、类型推断等问题。
英文:
You might consider just removing one layer of generics and write it as:
ValueTask<IRequestExecutionResult<T>> ExecuteAsync<T>(IRequest<T> request, CancellationToken cancel = default)
This should help with type inference . It is somewhat common to go a bit overboard with generics, and this can lead to issues with method resolution, type inference etc.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论