I need to invoke an overloaded method using reflection. My classes as below:
public static Transformer
{
//Overloaded method with generics parameter. First Transform Method
public static TranformerResult Transform<T>(object [] entities,
List<T> dataContract) where T:class
{
return transformerResult;
}
//Overloaded method without generics parameter. Second Transform Method
public static TranformerResult Transform(object entities,
Type dataContract)
{
return transformerResult;
}
}
public class TransformerResult
{
public List<T> GetTypes<T>() where T:class
{
}
}
I tried to invoke first Transform method with below syntax:
GetMethod(“Transform”,(BindingFlags.Static | BindingFlags.Public),
null, new Type[](){typeof(object[]),typeof(List<Type>}, null)
But I am getting second Transform method.
My intention is to invoke GetType on transformerResult . The transformerResult is an object which returns invocation of first transform method.
Can any one help me to write the C# code to achieve my intention?
Thanks, Mahir
I think that the second type in the array of types in the call to
GetMethod()
is confusing things. If you get an instance of theType
class of the class containing these methods, that does not include the actual generic parameter used to create that instance of the class (which it looks like isType
, based on your second code sample). Instead, it just knows that it has one generic parameter.I don't have a compiler in front of my currently, so unfortunately I can't try this out, but I would try to specify the equivalent of
typeof(List<T>)
for the second parameter (you might be able to get this by callingSystem.Collections.Generic.List.GetType()
, but I'm not positive).If that doesn't work, the only other option that I can think of is to call
Type.GetMethods(BindingFlags.Static | BindingFlags.Public)
, and search through the array yourself.The reason you're running into a problem is that the particular method you're looking for is generic. One of the types of the method is based off of the generic parameter of the method. This presents you with a bit of a catch 22. The generic parameter is tied to the method so you cannot properly construct the type array for the method until you have the method itself.
One solution for this specific scenario is the just grab the first generic method.
Unless this works:
typeof(List<>)
you're going to need to be a bit tricky with what you do, similar to what I had to do with this post: http://www.aaron-powell.com/posts/2010-04-08-reflection-and-generics.htmlEssentially using LINQ to search the collection of all
Transform
methods, you can't get back just the one you want natively.