Reputation: 16603
I'm writing a reflection tool that I'll use for invoking methods from various types, and I'm testing it on simple programs.
I'm curious as why it doesn't return my Main()
method on standard Visual Studio generated Program class
class Program
{
static void Main(string[] args)
{ return ; }
When I load type Program
, and call type.GetMethods()
; it returns 4 methods inherited from Object
: ToString
, GetHashCode
, GetType
and Equals
.
I'm guessing Main
is a special method as it's program's entry point, but there should be a way to retrieve its MethodInfo
. Is there a way to get it?
Upvotes: 1
Views: 3577
Reputation: 49970
GetMethods()
returns all the public methods of the current Type.
You have to use GetMethods(BindingFlags.Instance | BindingFlags.Static | BindingFlags.NonPublic)
More info on Type.GetMethods(BindingsFlags)
Upvotes: 3
Reputation: 3743
The problem is that Main() is private and static. Try this:
MethodInfo[] methods = typeof(Program).GetMethods(BindingFlags.Public
| BindingFlags.NonPublic
| BindingFlags.Static
| BindingFlags.Instance
);
Upvotes: 2
Reputation: 1058
Main() is not public by default:
type.GetMethods(BindingFlags.Static | BindingFlags.NonPublic);
Upvotes: 1
Reputation: 1499770
Your Main
method is private, so you need to include BindingFlags.NonPublic
.
(BindingFlags.Static
is included by default, but NonPublic
isn't.)
So:
var methods = type.GetMethods(BindingFlags.Public | BindingFlags.NonPublic |
BindingFlags.Static | BindingFlags.Instance);
(I'm assuming you want the public and instance methods as well, of course.)
Although Main
is identified as the entry point here, there's nothing else that's particularly special about it - you can find it in the same way as other methods, and invoke it too.
Upvotes: 8