我可以通过一个类型的对象泛型方法? [英] Can I pass a type object to a generic method?

查看:181
本文介绍了我可以通过一个类型的对象泛型方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有我的DataAccessLayer一个的FindAll方法,它看起来是这样的:

I have a FindAll method on my DataAccessLayer which looks like this:

public FindResult<T> FindAll<T>() where T : Entity, new()

和客户端code,有它需要使用迭代像这样调用的FindAll方法的类型[]数组:

and a client code that has a Type[] array which it needs to use to iteratively call the FindAll method with like this:

foreach (var type in typeArray)
{    
    var result = DataAccessLayer.FindAll<type>();
    ...

但关于类型或命名空间预期。该编译器的投诉有没有一种简单的方法来解决这个问题?我试着type.GetType()或typeof运算(类型),并没有工作。

but the compiler complaints about "Type or namespace expected".. Is there an easy way to get around this? I've tried type.GetType() or typeof(type) and neither worked.

提前感谢!

推荐答案

您可能需要使用反射来做到这一点,是这样的:

You may need to use Reflection to do this, something like this:

DataAccessLayer.GetType().GetMethod("FindAll<>").MakeGenericMethod(type).Invoke()

<一个href="http://www.arquitecturadesoftware.org/blogs/hugobatista/archive/2006/03/08/dynamically-calling-generic-methods-or-how-to-use-generics-through-cominterop.aspx">This博客文章还可能包含你所需要的信息。

This blog post may also contain the information you need.

这篇关于我可以通过一个类型的对象泛型方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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