如何获取使用顶级语句的C#9程序的反射类型信息?
假设我有一个用C#9编写的简单脚本,如下所示:如何获取使用顶级语句的C#9程序的反射类型信息?,c#,reflection,c#-9.0,toplevel-statement,C#,Reflection,C# 9.0,Toplevel Statement,假设我有一个用C#9编写的简单脚本,如下所示: using System; using System.IO; // What to put in the ??? var exeFolder = Path.GetDirectoryName(typeof(???).Assembly.Location); 在使用完整程序之前,我们可以使用Main类作为“指示符”类this和this.GetType()不可用,因为从技术上讲,它位于静态方法中。我现在怎么得到它 键入问题时我想到的一个解决方法是As
using System;
using System.IO;
// What to put in the ???
var exeFolder = Path.GetDirectoryName(typeof(???).Assembly.Location);
在使用完整程序之前,我们可以使用Main
类作为“指示符”类this
和this.GetType()
不可用,因为从技术上讲,它位于静态方法中。我现在怎么得到它
键入问题时我想到的一个解决方法是
Assembly.GetCallingAssembly()
:
它适用于我的情况,但我只能获取运行代码的
程序集
,而不能获取运行代码的类型信息。您也可以使用
一旦有了代码所在的程序集,就可以得到它,这是编译器生成的“Main
”方法。然后,您可以执行DeclaringType
以获取类型
:
Console.WriteLine(Assembly.GetEntryAssembly().EntryPoint.DeclaringType);
即使您不在顶层,上面的代码也会生成编译器生成的“Program
”类。我建议从正在执行的方法(Main
)开始:
如果您想要Type
,而不是TypeInfo
删除最后一种方法:
Type result = MethodBase
.GetCurrentMethod() // Executing method (e.g. Main)
.DeclaringType; // Type where it's declared (e.g. Program)
可能会尝试通过执行方法:MethodInfo.GetCurrentMethod().DeclaringType
您可能会看到,似乎是一个重复的候选人,我觉得非常遗憾,我无法将两个答案都标记为正确。我会标记另一个,因为它“更接近”我的问题,但你的答案仍然很好。谢谢你,我今天学到了一些新东西。
TypeInfo result = MethodBase
.GetCurrentMethod() // Executing method (e.g. Main)
.DeclaringType // Type where it's declared (e.g. Program)
.GetTypeInfo();
Type result = MethodBase
.GetCurrentMethod() // Executing method (e.g. Main)
.DeclaringType; // Type where it's declared (e.g. Program)