开发者

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

开发者 https://www.devze.com 2022-12-18 01:13 出处:网络
This question already has answers here: How do I use reflection to call a generic method? 开发者_如何转开发(8 answers)
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

精彩评论

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

关注公众号