【问题标题】:How do I get the Reflection TypeInfo of a C# 9 program that use Top-level statements?如何获取使用顶级语句的 C# 9 程序的反射类型信息?
【发布时间】:2021-03-17 17:20:49
【问题描述】:

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

using System;
using System.IO;

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

以前,在完整的程序中,我们可以使用Main 类作为“指标”类。 thisthis.GetType() 不可用,因为从技术上讲,它位于静态方法中。我现在如何获得它?


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

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

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

【问题讨论】:

标签: c# reflection c#-9.0 toplevel-statement


【解决方案1】:

您也可以使用GetEntryAssembly 获取程序集。

一旦你有了你的代码所在的程序集,你就可以得到它的EntryPoint,这是编译器生成的“Main”方法。然后您可以通过DeclaringType 获取Type

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

即使你不在顶层,上面也应该得到编译器生成的“Program”类。

【讨论】:

  • 当我无法将两个答案都标记为正确时,我感到非常难过。我会标记另一个,因为它“更接近”我的问题,但你的答案仍然很好。谢谢,我今天学到了新东西。
【解决方案2】:

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

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

如果你想要Type,而不是TypeInfo,请放弃最后一个方法:

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

 

【讨论】:

    【解决方案3】:

    对于 C# 10 (See 4th point in the breaking changes) 编译器为顶级语句生成 Program 类,以便您可以使用它:

    Console.WriteLine(typeof(Program).FullName);
    

    虽然目前docs 声明:

    请注意,名称“Program”和“Main”仅用于说明目的,编译器使用的实际名称取决于实现,类型和方法都不能通过源代码中的名称引用。

    ASP.NET Core 集成测试文档依赖于这个类的命名约定。

    【讨论】:

      猜你喜欢
      • 2023-01-27
      • 1970-01-01
      • 2021-12-25
      • 2011-11-13
      • 2017-06-19
      • 2012-01-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多