C#泛型:通过去重简化方法声明

huangapple go评论59阅读模式
英文:

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&lt;IRequestExecutionResult&lt;T&gt;&gt; ExecuteAsync&lt;T&gt;(IRequest&lt;T&gt; 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.

huangapple
  • 本文由 发表于 2023年5月22日 23:00:31
  • 转载请务必保留本文链接:https://go.coder-hub.com/76307486.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定