Home > Blockchain >  Reflection in .NET
Reflection in .NET

Time:09-22

class Program
{
    static void Main(string[] args)
    {
        Type doub = typeof(Doub);
        object result = doub.InvokeMember("Call", BindingFlags.InvokeMethod, null, null, new object[] { });
    }
}

public class Doub
{
    public Collection<string> Call()
    {
        Collection<string> collection = new Collection<string>();
        return collection;
    }

    public Collection<T> Call<T>()
    {
        Collection<T> collection = new Collection<T>();
        return collection;
    }
}

I tried to call the Call method, but the program cannot figure out which method to call. Error: (System.Reflection.AmbiguousMatchException: "Ambiguous match found). How can you call exactly the Call() method of the class?

CodePudding user response:

You need to use a different way to get the method to execute. For example, the Type object has a method called GetMethod with various overloads, you could use the one that allows you to specify how many generic parameters the method has, for example:

Type doub = typeof(Doub);
var callMethod = doub.GetMethod("Call", 0, new Type[] {});

// You need an instance of the object to call the method on
var x = new Doub();

var result = callMethod.Invoke(x, new object[] {});
  • Related