我可以通过一个类型的对象泛型方法?可以通过、对象、类型、方法

2023-09-04 00:07:17 作者:樱花祭

我有我的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()

This博客文章还可能包含你所需要的信息。

This blog post may also contain the information you need.