C# 具有多个约束的通用方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/588643/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Generic method with multiple constraints
提问by Martin
I have a generic method which has two generic parameters. I tried to compile the code below but it doesn't work. Is it a .NET limitation? Is it possible to have multiple constraints for different parameter?
我有一个泛型方法,它有两个泛型参数。我试图编译下面的代码,但它不起作用。它是 .NET 限制吗?是否可以对不同的参数有多个约束?
public TResponse Call<TResponse, TRequest>(TRequest request)
where TRequest : MyClass, TResponse : MyOtherClass
采纳答案by LukeH
It is possible to do this, you've just got the syntax slightly wrong. You need a where
for each constraint rather than separating them with a comma:
这是可能的,你只是语法有点错误。where
每个约束都需要一个,而不是用逗号分隔它们:
public TResponse Call<TResponse, TRequest>(TRequest request)
where TRequest : MyClass
where TResponse : MyOtherClass
回答by maytham-???????
In addition to the main answer by @LukeH, I have issue with dependency injection, and it took me some time to fix this. It is worth to share, for those who face the same issue:
除了@LukeH 的主要回答之外,我还有依赖注入的问题,我花了一些时间来解决这个问题。值得分享,对于那些面临同样问题的人:
public interface IBaseSupervisor<TEntity, TViewModel>
where TEntity : class
where TViewModel : class
It is solved this way. in containers/services the key is typeof and the comma (,)
就这样解决了。在容器/服务中,键是 typeof 和逗号 (,)
services.AddScoped(typeof(IBaseSupervisor<,>), typeof(BaseSupervisor<,>));
This was mentioned in this answer.
这个答案中提到了这一点。
回答by Hamit YILDIRIM
In addition to the main answer by @LukeH with another usage, we can use multiple interfaces instead of class. (One class and n count interfaces) like this
除了@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