通用方法,多约束 [英] Generic method with multiple constraints

查看:139
本文介绍了通用方法,多约束的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有它有两个泛型参数的通用方法。我试图编译下面的code,但它不工作。它是一个.NET的限制?是否有可能有多个约束不同的参数?

 公共TResponse呼叫< TResponse,TRequ​​est>(TRequ​​est要求)
  其中,TRequ​​est:MyClass的,TResponse:MyOtherClass
 

解决方案

这是可能做到这一点,你拿到的语法稍有不妥。你需要一个其中,每个约束而不是将它们用逗号分隔:

 公共TResponse呼叫< TResponse,TRequ​​est>(TRequ​​est要求)
    其中,TRequ​​est:MyClass的
    其中,TResponse:MyOtherClass
 

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?

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

解决方案

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

这篇关于通用方法,多约束的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆