我可以将类型对象传递给泛型方法吗? [重复]

时间:2022-04-05 22:28:13

This question already has an answer here:

这个问题在这里已有答案:

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

我的DataAccessLayer上有一个FindAll方法,如下所示:

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

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

和一个客户端代码有一个Type []数组,它需要用来迭代调用FindAll方法,如下所示:

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

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.

但编译器抱怨“预期的类型或命名空间”..有没有一种简单的方法来解决这个问题?我尝试过type.GetType()或typeof(type),但都没有用。

Many thanks in advance!

提前谢谢了!

2 个解决方案

#1


13  

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

您可能需要使用Reflection来执行此操作,如下所示:

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

This blog post may also contain the information you need.

此博文可能还包含您需要的信息。

#2


3  

When using generics, the type needs to be resolveable at compile time. You are trying to supply the type at runtime.

使用泛型时,类型需要在编译时解析。您正尝试在运行时提供该类型。

#1


13  

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

您可能需要使用Reflection来执行此操作,如下所示:

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

This blog post may also contain the information you need.

此博文可能还包含您需要的信息。

#2


3  

When using generics, the type needs to be resolveable at compile time. You are trying to supply the type at runtime.

使用泛型时,类型需要在编译时解析。您正尝试在运行时提供该类型。