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?
TArgs
but then you're invoking it with two parameters (someVar1
andsomeVar2
). If they use two parameters then specify both of them. – MateuszWhere(...).FirstOrDefault()
,FirstOrDefault(...)
will work just fine. – TheLethalCodernew Type[] {typeOfFirstArg, typeof(TArgs)}
because right now you're looking for a method that takes a single parameter of typeTArgs
and there is no such method thus you getnull
– Sergey.quixoticaxis.Ivanovthis.AsDynamic().MyPrivateStaticMethod(someVar1,someVar2)
– Ofir Winegarten