【发布时间】: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 类作为“指标”类。 this 和 this.GetType() 不可用,因为从技术上讲,它位于静态方法中。我现在如何获得它?
我在输入问题时想到的解决方法是Assembly.GetCallingAssembly():
var exeFolder = Path.GetDirectoryName(Assembly.GetCallingAssembly().Location);
它适用于我的情况,但我只能得到 Assembly,而不是运行代码的 TypeInfo。
【问题讨论】:
-
可以尝试通过执行方法:
MethodInfo.GetCurrentMethod().DeclaringType
标签: c# reflection c#-9.0 toplevel-statement