ferodss
ferodss

Reputation: 668

How can I get a protected method via reflection matching name and parameters type?

Before dotnet core we were able to do

var member = type.GetMethod(name, bindingFlags, null, argtypes, null);

To get access to a method matching its name and parameters type, in dotnet core they removed this overload, now I can only get by name && binding flags OR name && parameters type (see), but not like before.

There is a new method GetRuntimeMethods which returns IEnumerable<MethodInfo> and includes non public methods but I can't filter by parameters type.

There is another method GetRuntimeMethod which I can filter by parameters type but it doesn't include non public methods.

I already tried something like this, but fails

var member = type.GetRuntimeMethods().Where(m =>
m.Name == name && (m.GetParameters().Select(p => p.GetType()).ToArray() == argtypes)).FirstOrDefault();

Is there a way to get a method by its name and parameters type?

Upvotes: 2

Views: 614

Answers (1)

svick
svick

Reputation: 244968

Yes, that overload is indeed missing. What you can use is to use GetMethods() and filter the output the way you want. Your attempt is close, except you can't compare arrays using ==:

var method = type.GetMethods().FirstOrDefault(m =>
    m.Name == name && m.GetParameters().Select(p => p.ParameterType).SequenceEqual(argTypes));

Upvotes: 2

Related Questions