c# - 我需要一个永远不会返回 null 的 `Assembly.GetEntryAssembly()` 的替代方案

标签 c# .net system.reflection entry-point

我需要找到开始执行托管代码的程序集。

// using System.Reflection;
Assembly entryAssembly = Assembly.GetEntryAssembly();

这似乎是要走的路,但是 MSDN reference page for Assembly.GetEntryAssembly声明此方法[c]从非托管代码调用时返回 null。”

在那种情况下,我想知道非托管代码调用了哪个程序集。

有没有一种可靠的方法可以做到这一点,即总是返回一个非空的 Assembly 引用?

最佳答案

到目前为止我能想到的最好的是以下,它应该在单线程场景中工作:

// using System.Diagnostics;
// using System.Linq; 
Assembly entryAssembly = new StackTrace().GetFrames().Last().GetMethod().Module.Assembly;

(上面的代码片段是为了便于理解而优化的,而不是为了执行速度或内存效率。)

关于c# - 我需要一个永远不会返回 null 的 `Assembly.GetEntryAssembly()` 的替代方案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14165785/

相关文章:

c# - 错误 : List<int> does not have the matching of 'System. Collections.Generic.IEnumerable<int>

c# - 在完全初始化结构之前访问结构的字段

c# - 当外部库不向后兼容时检查属性是否存在

c# - 使用反射将值写入 struct var 成员不起作用,但它适用于类

c# - 通过反射生成嵌套类的实例 C#

c# - 在执行时创建目录 MVC 6

c# - 是否可以计算回发中的按钮点击次数

c# - SPGridView 中的组总计

c# - 当没有列是动态的时将 DataTable 转换为列表

c# - 获取阿拉伯月份的英文名称