具有多个约束的通用方法 [英] Generic method with multiple constraints

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

问题描述

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

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

推荐答案

这是可能的,只是你的语法有点错误.您需要一个 where 用于每个约束,而不是用逗号分隔它们:

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天全站免登陆