【问题标题】:Generic method with multiple constraints具有多个约束的通用方法
【发布时间】:2021-08-22 05:27:15
【问题描述】:

我有一个具有两个泛型参数的泛型方法。我试图编译下面的代码,但它不起作用。它是 .NET 限制吗?是否可以对不同的参数有多个约束?

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

【问题讨论】:

    标签: c# generics .net-3.5


    【解决方案1】:

    可以这样做,只是语法有点错误。您需要为每个约束使用where,而不是用逗号分隔它们:

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

    【讨论】:

      【解决方案2】:

      除了@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
      

      【讨论】:

        【解决方案3】:

        除了@LukeH 的主要回答之外,我还遇到了依赖注入问题,我花了一些时间来解决这个问题。对于那些面临同样问题的人来说,值得分享:

        public interface IBaseSupervisor<TEntity, TViewModel> 
            where TEntity : class
            where TViewModel : class
        

        这样就解决了。在容器/服务中,键是 typeof 和逗号 (,)

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

        answer 中提到了这一点。

        【讨论】:

        【解决方案4】:

        每个约束都需要单独一行,如果单个泛型参数有更多约束,则需要用逗号分隔。

        public TResponse Call<TResponse, TRequest>(TRequest request)
            where TRequest : MyClass 
            where TResponse : MyOtherClass, IOtherClass
        
        

        根据评论编辑

        【讨论】:

        • 这个答案是不正确的,无论是在 MyClass 后面的逗号中(请参阅最受好评的答案),而且声明约束需要在单独的行中。我会修复它,但编辑队列已满。
        • 谢谢@ToddWest。我已经删除了MyClass 之后的附加逗号
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-18
        • 1970-01-01
        • 1970-01-01
        • 2018-07-22
        • 1970-01-01
        相关资源
        最近更新 更多