0

I have a assembly which contains a class. That class has two methods

public IEnumerable Invoke();
public IEnumerable<T> Invoke<T>();

I dynamically load the assembly

Assembly as = Assembly.Load("MyAssemblyName, Version= 6.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35")
Type type = as.GetType("MyClass");
object myObject= Activator.CreateInstance(type);

IEnumerable test= (IEnumerable)myObject.GetType().InvokeMember("Invoke", BindingFlags.InvokeMethod, null, myObject, null);

I want this method is called: public IEnumerable Invoke();

when I run the program I got an error: Ambiguous match found

So what needs to do to remove the ambiguity, so the non-generic method to be called?

Thanks in advance.

phoog
  • 42,068
  • 6
  • 79
  • 117
Larry G
  • 1
  • 1
  • @Luaan that would try to invoke an IEnumerable member called "Invoke" which does not exist. – phoog Sep 11 '14 at 15:33
  • Yeah, I missed that point. Why not create an interface that has those `Invoke` methods and then call that without having to use reflection in the first place? – Luaan Sep 11 '14 at 15:34
  • @Luaan Obviously this is toy code to demonstrate the problem. – Casey Sep 11 '14 at 15:37
  • possible duplicate of [How to get MethodInfo of a generic method on a non generic .NET type?](http://stackoverflow.com/questions/1624817/how-to-get-methodinfo-of-a-generic-method-on-a-non-generic-net-type) – Steve Guidi Sep 11 '14 at 15:38

1 Answers1

9

You can find the method by calling GetMethods and check ContainsGenericParameters is false. Optionally you could also check for parameter count to zero.

var method = yourType.GetMethods()
    .Where(x => x.Name == "Invoke")
    .First(x => !x.ContainsGenericParameters);
method.Invoke(myObject, null);
Sriram Sakthivel
  • 72,067
  • 7
  • 111
  • 189