Generic method with multiple constraints

后端 未结 3 1631
迷失自我
迷失自我 2020-11-27 12:50

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 co

相关标签:
3条回答
  • 2020-11-27 13:04

    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:

    public TResponse Call<TResponse, TRequest>(TRequest request)
        where TRequest : MyClass
        where TResponse : MyOtherClass
    
    0 讨论(0)
  • 2020-11-27 13:10

    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

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

    or

    public TResponse Call<TResponse, TRequest>(TRequest request)
      where TRequest : IMyClass,IMyOtherClass
    
    0 讨论(0)
  • 2020-11-27 13:17

    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:

    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 (,)

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

    This was mentioned in this answer.

    0 讨论(0)
提交回复
热议问题