无法通过 .NET 5 顶级调用使用反射找到 Main 方法

Cannot find Main method using reflection with .NET 5 top level calls

var pt = Type.GetType("<Program>$");
var m = pt.GetMethod("<Main>$", BindingFlags.Static);
// m is null

好的,我抓住了 Program class,这很好用。但是我去抓取Main方法时,系统找不到,也不在pt.GetMembers()中。怎么回事?

您只需指定您想要查看非public 成员:

using System;
using System.Reflection;

var pt = Type.GetType("<Program>$");
var m = pt.GetMethod("<Main>$", BindingFlags.Static | BindingFlags.NonPublic);
Console.WriteLine(m); // Prints Void <Main>$(System.String[])

同样使用 GetMembers,您需要指定您想要 public 和非 public 成员:

using System;
using System.Reflection;

var pt = Type.GetType("<Program>$");
var flags =
    BindingFlags.Public | BindingFlags.NonPublic |
    BindingFlags.Instance | BindingFlags.Static;
foreach (var member in pt.GetMembers(flags))
{
    Console.WriteLine(member);
}