我有一个泛型方法,它有两个泛型参数。我试图编译下面的代码,但它不起作用。它是.NET的限制吗?对于不同的参数是否可能有多个约束?

public TResponse Call<TResponse, TRequest>(TRequest request)
  where TRequest : MyClass, TResponse : MyOtherClass

这是有可能的,只是语法有点错误。你需要为每个约束加上一个where,而不是用逗号分隔:

public TResponse Call<TResponse, TRequest>(TRequest request)
    where TRequest : MyClass
    where TResponse : MyOtherClass

除了@LukeH的主要回答,我有一个依赖注入的问题,我花了一些时间来解决这个问题。对于那些面临同样问题的人来说,这是值得分享的:

public interface IBaseSupervisor<TEntity, TViewModel> 
    where TEntity : class
    where TViewModel : class

它是这样解决的。在容器/服务中,键是typeof和逗号(,)

services.AddScoped(typeof(IBaseSupervisor<,>), typeof(BaseSupervisor<,>));

在这个回答中提到了这一点。

除了@LukeH给出的主要答案外,我们还可以使用多个接口来代替类。(一个类和n个接口)

public TResponse Call<TResponse, TRequest>(TRequest request)
  where TRequest : MyClass, IMyOtherClass, IMyAnotherClass

or

public TResponse Call<TResponse, TRequest>(TRequest request)
  where TRequest : IMyClass,IMyOtherClass

每个约束都需要在自己的行上,如果单个通用参数有多个约束,则需要用逗号分隔。

public TResponse Call<TResponse, TRequest>(TRequest request)
    where TRequest : MyClass 
    where TResponse : MyOtherClass, IOtherClass

按评论编辑