1
votes

I have public static class MyClass where I have 2 method overloads (basically method overload accepts MyType1 and another overload accepts MyType2, these types are inherited from MyTypeBase).

And I'm calling one of overloads from third method (MyPrivateStaticMethod()), which accepts generics (where TArgs : MyTypeBase), so that I can have one method (MyPrivateStaticMethod()) to handle all the types that inherit same base type.

// Get Method
var myPrivateStaticMethod =
    typeof(MyClass)
    .GetMethod(
        "MyPrivateStaticMethod",
        BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic,
        null,
        new Type[]
        {
            typeof(TArgs),
        },
        null
    );

if (myPrivateStaticMethod == null)
{
    // Handle not overloaded method
}

// Trigger method with needed type
myPrivateStaticMethod.Invoke(
    null, 
    new object[] 
    {
        someVar1, // Let's say this is int
        somevar2  // And this is MyType1 or MyType2, 
                  // depending on what type we do have there
});

The problem is that I can't find method by so. On the other hand if I queue by LINQ: (...).GetMethods(...).Where(x => x.Name == "MyMethodNameIWantToFind").FirstOrDefault(); it does find method, but problem is it doesn't find overload I need

(with right type - in my case MyType1 or MyType2, it takes first method it finds (MyType1), because I declare this overload earlier than second, this is not useful when I have passed MyType2 in runtime to that method).

Problem: I need to find private static method with multiple parameters in signature inside of current class. Have I missed something inside my .GetMethod() use?

1
You're looking for the method that takes one parameter of type TArgs but then you're invoking it with two parameters ( someVar1 and someVar2 ). If they use two parameters then specify both of them.Mateusz
Side note: No need for Where(...).FirstOrDefault(), FirstOrDefault(...) will work just fine.TheLethalCoder
you should use new Type[] {typeOfFirstArg, typeof(TArgs)} because right now you're looking for a method that takes a single parameter of type TArgs and there is no such method thus you get nullSergey.quixoticaxis.Ivanov
@PavelSanatov Instead of update just post an answer with updated and working code, then accept it for the future visitors.Mateusz
BTW, There is a library called ReflectionMagic that can take all this pain away: this.AsDynamic().MyPrivateStaticMethod(someVar1,someVar2)Ofir Winegarten

1 Answers

0
votes

Problem was with my new Type[] {...} array inside of .GetMethod(). There was only one type defined instead of my count of object types I'm passing to MyPrivateStaticMethod() method.