如何在泛型方法调用中使用Type变量(C#)

编程入门 行业动态 更新时间:2024-10-28 16:23:47
本文介绍了如何在泛型方法调用中使用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#)

本文发布于:2023-11-10 10:23:26,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1575096.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:变量   方法   如何在   Type

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!