【发布时间】:2021-08-22 05:27:15
【问题描述】:
我有一个具有两个泛型参数的泛型方法。我试图编译下面的代码,但它不起作用。它是 .NET 限制吗?是否可以对不同的参数有多个约束?
public TResponse Call<TResponse, TRequest>(TRequest request)
where TRequest : MyClass, TResponse : MyOtherClass
【问题讨论】:
我有一个具有两个泛型参数的泛型方法。我试图编译下面的代码,但它不起作用。它是 .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 的主要答案还有另一种用法,我们可以使用多个接口而不是类。 (一个类和n个接口)像这样
public TResponse Call<TResponse, TRequest>(TRequest request)
where TRequest : MyClass, IMyOtherClass, IMyAnotherClass
或
public TResponse Call<TResponse, TRequest>(TRequest request)
where TRequest : IMyClass,IMyOtherClass
【讨论】:
除了@LukeH 的主要回答之外,我还遇到了依赖注入问题,我花了一些时间来解决这个问题。对于那些面临同样问题的人来说,值得分享:
public interface IBaseSupervisor<TEntity, TViewModel>
where TEntity : class
where TViewModel : class
这样就解决了。在容器/服务中,键是 typeof 和逗号 (,)
services.AddScoped(typeof(IBaseSupervisor<,>), typeof(BaseSupervisor<,>));
answer 中提到了这一点。
【讨论】:
每个约束都需要单独一行,如果单个泛型参数有更多约束,则需要用逗号分隔。
public TResponse Call<TResponse, TRequest>(TRequest request)
where TRequest : MyClass
where TResponse : MyOtherClass, IOtherClass
根据评论编辑
【讨论】:
MyClass 之后的附加逗号