我有一个通用方法,其中包含两个通用参数。我尝试编译下面的代码,但它不能工作。这是.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<,>));
这在这个答案中提到了。
public TResponse Call<TResponse, TRequest>(TRequest request)
where TRequest : MyClass
where TResponse : MyOtherClass, IOtherClass
根据评论进行编辑
MyClass
后面的额外逗号。 - mybrave
where T : MyClass where T : MyOtherClass
? - WDUKwhere T : MyClass, IMyInterface
是有效的,但where T : MyClass, MyOtherClass
是无效的。 - undefined