How do I get the Reflection TypeInfo of a C# 9 program that use Top-level statements?

∥☆過路亽.° 提交于 2020-12-12 05:39:42

问题


Assume I have a simple script writing in C# 9 like this:

using System;
using System.IO;

// What to put in the ???
var exeFolder = Path.GetDirectoryName(typeof(???).Assembly.Location);

Before, with the full program, we can use the Main class as an "indicator" class. this and this.GetType() is not available because technically it's inside a static method. How do I get it now?


A workaround I thought of while typing the question is Assembly.GetCallingAssembly():

var exeFolder = Path.GetDirectoryName(Assembly.GetCallingAssembly().Location);

It works for my case, but I can only get the Assembly, not the TypeInfo that in which the code is running.


回答1:


I suggest starting from the method which is executing (Main):

TypeInfo result = MethodBase
  .GetCurrentMethod() // Executing method         (e.g. Main)
  .DeclaringType      // Type where it's declared (e.g. Program)
  .GetTypeInfo();    

If you want Type, not TypeInfo drop the last method:

Type result = MethodBase
  .GetCurrentMethod() // Executing method         (e.g. Main)
  .DeclaringType;     // Type where it's declared (e.g. Program)

 



回答2:


You can also get the assembly using GetEntryAssembly.

Once you have the assembly that your code is in, you can get its EntryPoint, which is the compiler-generated "Main" method. You can then do DeclaringType to get the Type:

Console.WriteLine(Assembly.GetEntryAssembly().EntryPoint.DeclaringType);

The above should get the compiler-generated "Program" class even if you are not at the top level.



来源:https://stackoverflow.com/questions/65164165/how-do-i-get-the-reflection-typeinfo-of-a-c-sharp-9-program-that-use-top-level-s

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