本文介绍了这对于获取程序集位置,GetAssembly()。Location或GetExecutingAssembly()。Location更好的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请建议哪个是执行程序集位置的最佳选择。

Please suggest which is the best to getting executing assembly location.

Assembly.GetAssembly(typeof(NUnitTestProject.RGUnitTests)).Location

Assembly.GetExecutingAssembly().Location

请提出哪个更好的建议。我还可以使用 GetEntryAssembly()吗?

Please suggest which can be better. Can I use GetEntryAssembly() also?

推荐答案

这取决于什么 Assembly.GetAssembly 返回声明了 type 的程序集。
Assembly.GetExecutingAssembly 返回执行当前代码的程序集。
Assembly.GetEntryAssembly 返回进程可执行文件,请记住,这可能不是您的可执行文件。例如:

it depends on what you want.. Assembly.GetAssembly return the assembly where type is declared.Assembly.GetExecutingAssembly returns the assembly where the current code is being executed on.and Assembly.GetEntryAssembly return the process executable, keep in mind that is may not be your executable. ex:

想象您的代码在 myexecutable.exe 上,并且您遇到这种情况。

imagine your code is on myexecutable.exe and you have the this scenario.

trdparty.exe ->使用 Assembly.LoadFile 加载可执行文件并通过反射运行一些代码

trdparty.exe -> uses Assembly.LoadFile to load your executable and run some code by reflection

myexecutable.exe ->使用类型 MyClass

,但 trdparty.exe 会修补您的代码,以使用新版本的 MyClass 位于 Patch.dll

but the trdparty.exe patches your code to use the new version of MyClass located in Patch.dll

现在,如果您运行您自己的应用程序都可以自己得到结果

So now.. if you run your application all by it self you get this result

Assembly.GetAssembly(typeof(MyClass)) -> myexecutable.exe
Assembly.GetExecutingAssembly() -> myexecutable.exe
Assembly.GetEntryAssembly() -> myexecutable.exe

但是如果您使用的是以前的方案,则可以得到

but if you have the previous scenario you get

Assembly.GetAssembly(typeof(MyClass)) -> Patch.dll
Assembly.GetExecutingAssembly() -> myexecutable.exe
Assembly.GetEntryAssembly() -> trdparty.exe

因此,应使用提供所需结果的响应作为响应。
的答案似乎很明显,它是 Assembly.GetExecutingAssembly(),但有时不是。.想象您正在尝试加载与可执行文件关联的application.config 文件。那么路径很可能应该为 Assembly.GetEntryAssembly()。Location ,以始终获取路径我说的过程

so as a response you should use the one that provides the result that you want..the answer may seem obvious that it is Assembly.GetExecutingAssembly() but sometimes is not.. imagine that you are trying to load the application.config file associated with the executable.. then the path will most probably should be Assembly.GetEntryAssembly().Location to always get he path of the "process"

取决于场景和目的...

as I said depends on the scenario.. and the purpose...

这篇关于这对于获取程序集位置,GetAssembly()。Location或GetExecutingAssembly()。Location更好的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-06 02:10