如何在泛型方法调用中使用Type变量(C#) [英] How to use a Type variable in a generic method call (C#)

查看:223
本文介绍了如何在泛型方法调用中使用Type变量(C#)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个传递给方法的类型变量 t ,我希望在调用 IQueryable.Join >如下所示:

$ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $> queryResult.Join< Type1,Type2,t,Type3>(items,outerSelector,innerSelector ,(a,b)=> a);

它显然不起作用。我应该怎么做 t 以达到我的目的?感谢!

解决方案

基本上你必须用反射来调用方法:


  • 使用 Type.GetMethod

  • 获取泛型方法模板。Call MakeGenericMethod 传入4个类型参数

  • 调用传入常规参数的方法



这是一个痛苦:($ / b $ b

I have a Type variable t passed into a method, and I want to use it as a generic parameter when calling IQueryable.Join like the following

queryResult.Join<Type1, Type2, t, Type3>( items, outerSelector, innerSelector, ( a, b) => a);

It obviously doesn't work. What should I do to t in order to achieve what I intended? Thanks!

解决方案

Basically you've got to call the method with reflection:

  • Get the generic method template with Type.GetMethod
  • Call MakeGenericMethod passing in your 4 type parameters
  • Invoke the method passing in the regular arguments

It's a pain :(

这篇关于如何在泛型方法调用中使用Type变量(C#)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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