如何获取使用顶级语句的 C# 9 程序的反射类型信息?

如何获取使用顶级语句的 C# 9 程序的反射类型信息?

问题描述:

假设我有一个用 C# 9 编写的简单脚本,如下所示:

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

之前,对于完整的程序,我们可以使用 Main 类作为指示器";班级.thisthis.GetType() 不可用,因为从技术上讲,它位于静态方法中.我现在如何获得它?

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?

我在输入问题时想到的解决方法是 Assembly.GetCallingAssembly():

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

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

它适用于我的情况,但我只能获得 Assembly,而不是运行代码的 TypeInfo.

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

我建议从正在执行的 method (Main) 开始:

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

如果你想要 Type,而不是 TypeInfo 删除最后一个方法:

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)