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

一笑奈何 提交于 2020-12-31 05:02:59

问题


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

Okay, I grab the Program class, this works fine. But when I go to grab the Main method, system cannot find it, and it's not in pt.GetMembers() either. What's going on?


回答1:


You just need to specify that you want to see non-public members:

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[])

Likewise using GetMembers, you need to specify you want public and non-public members:

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);
}


来源:https://stackoverflow.com/questions/64966831/cannot-find-main-method-using-reflection-with-net-5-top-level-calls

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!