我需要一种替代`Assembly.GetEntryAssembly()`永远不会返回null [英] I need an alternative to `Assembly.GetEntryAssembly()` that never returns null

查看:739
本文介绍了我需要一种替代`Assembly.GetEntryAssembly()`永远不会返回null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在其中找到管理code开始执行的程序集。

I need to find the assembly in which managed code execution started.

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

这似乎是一段路要走,但对于 MSDN参考页面 Assembly.GetEntryAssembly 指出,这种方法的[C]从非托管code时调用的返回null。

This seems like the way to go, but the MSDN reference page for Assembly.GetEntryAssembly states that this method "[c]an return null when called from unmanaged code."

在这种情况下,我想知道哪些组件被称为非托管code。

In that case, I would like to know which assembly was called by unmanaged code.

是否有这样做的可靠方法,也就是一个总是返回一个非空的组装参考?

Is there a reliable way of doing this, i.e. one that always returns a non-null Assembly reference?

推荐答案

我认为到目前为止的最好的是以下,这应该在一个单线程的情况:

The best I could think of so far is the following, which should work in a single-threaded scenario:

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

(以上片断为了易于理解优化,而不是为了执行速度或存储器效率。)

(The above snippet is optimized for ease of understanding, not for execution speed or memory efficiency.)

这篇关于我需要一种替代`Assembly.GetEntryAssembly()`永远不会返回null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆