lundi 29 juin 2015

c# Call generic method dynamically with reflection, which has a same method sign,non-generic version in the method table [duplicate]

Say I have a class like this:

public class MyTestClass<T>
{
    public void DoSomething(object o)
    {
        Logger.Debug("Non-generic version called.");
    }

    public void DoSomething<T>(T o)
    {
        Logger.Debug("Generic version called.");
    }
}

If I create an instance with type:MyTestClass<Object>, how could I call its generic version using reflection?

In following code, I can get two methodInfo with same MethodName("DoSomething") and ParamterType(Object), is there any flag can help me judge which one is the generic version?

[Test]
public void TestGenericClass()
{
    var o = new MyTestClass<object>();
    var t = o.GetType();

    var methodInfos = o.GetType().GetMethods();

    //Print MethodInfo
    PrintMethodInfo(methodInfos);

    //throw System.Reflection.AmbiguousMatchException here: Ambiguous matching in method resolution
    var m = t.GetMethod("DoSomething");

}





Aucun commentaire:

Enregistrer un commentaire