哪个更适合获取程序集位置,GetAssembly().Location或GetExecutingAssembly().位置

Nee*_*bey 16 c# .net-assembly

请建议哪个是最好的执行装配位置.

Assembly.GetAssembly(typeof(NUnitTestProject.RGUnitTests)).Location
Run Code Online (Sandbox Code Playgroud)

要么

Assembly.GetExecutingAssembly().Location 
Run Code Online (Sandbox Code Playgroud)

请建议哪个更好.我GetEntryAssembly()也可以用吗?

Cal*_*GSM 36

这取决于你想要什么.. Assembly.GetAssembly返回type声明的程序集. Assembly.GetExecutingAssembly返回current code正在执行的程序集.并Assembly.GetEntryAssembly返回process executable,请记住,这可能不是您的可执行文件.例如:

想象你的代码已经开启myexecutable.exe,你有这种情况.

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

myexecutable.exe - >使用类型 MyClass

trdparty.exe补丁代码中使用的新版本MyClass位于Patch.dll

所以现在..如果你自己运行你的应用程序,你会得到这个结果

Assembly.GetAssembly(typeof(MyClass)) -> myexecutable.exe
Assembly.GetExecutingAssembly() -> myexecutable.exe
Assembly.GetEntryAssembly() -> myexecutable.exe
Run Code Online (Sandbox Code Playgroud)

但如果你有上一个场景,你会得到

Assembly.GetAssembly(typeof(MyClass)) -> Patch.dll
Assembly.GetExecutingAssembly() -> myexecutable.exe
Assembly.GetEntryAssembly() -> trdparty.exe
Run Code Online (Sandbox Code Playgroud)

所以作为一个响应,你应该使用提供你想要的结果的那个..答案可能看起来很明显,Assembly.GetExecutingAssembly()但有时却不是......想象你正在尝试加载application.config与可执行文件相关的文件..然后路径很可能应该Assembly.GetEntryAssembly().Location总是让他走上"过程"的道路

正如我所说,取决于场景..和目的......