开发者

Can I pass a type object to a generic method? [duplicate]

This question already has answers here: How do I use reflection to call a generic method? 开发者_如何转开发 (8 answers) Closed 8 years ago.

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

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:

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.

Many thanks in advance!


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

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

This blog post may also contain the information you need.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜