Mar*_*tin 235 c# generics .net-3.5
我有一个泛型方法,它有两个通用参数.我试图编译下面的代码,但它不起作用.它是.NET限制吗?是否可以为不同的参数设置多个约束?
public TResponse Call<TResponse, TRequest>(TRequest request)
where TRequest : MyClass, TResponse : MyOtherClass
Run Code Online (Sandbox Code Playgroud)
Luk*_*keH 381
有可能这样做,你的语法略有错误.您需要where
为每个约束而不是用逗号分隔它们:
public TResponse Call<TResponse, TRequest>(TRequest request)
where TRequest : MyClass
where TResponse : MyOtherClass
Run Code Online (Sandbox Code Playgroud)
Ham*_*RIM 16
除了@LukeH 的主要答案还有另一种用法,我们可以使用多个接口而不是类。(一类和n计数接口)像这样
public TResponse Call<TResponse, TRequest>(TRequest request)
where TRequest : MyClass, IMyOtherClass, IMyAnotherClass
Run Code Online (Sandbox Code Playgroud)
或者
public TResponse Call<TResponse, TRequest>(TRequest request)
where TRequest : IMyClass,IMyOtherClass
Run Code Online (Sandbox Code Playgroud)
除了@LukeH 的主要回答之外,我还有依赖注入的问题,我花了一些时间来解决这个问题。值得分享,对于那些面临同样问题的人:
public interface IBaseSupervisor<TEntity, TViewModel>
where TEntity : class
where TViewModel : class
Run Code Online (Sandbox Code Playgroud)
就这样解决了。在容器/服务中,键是 typeof 和逗号 (,)
services.AddScoped(typeof(IBaseSupervisor<,>), typeof(BaseSupervisor<,>));
Run Code Online (Sandbox Code Playgroud)
这个答案中提到了这一点。
每个约束都需要在自己的行上,如果单个泛型参数有多个约束,那么它们需要用逗号分隔。
public TResponse Call<TResponse, TRequest>(TRequest request)
where TRequest : MyClass
where TResponse : MyOtherClass, IOtherClass
Run Code Online (Sandbox Code Playgroud)
根据评论编辑
归档时间: |
|
查看次数: |
76849 次 |
最近记录: |