Can I pass a type object to a generic method? [duplicate]
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.
精彩评论