如何在运行时检测丢失的 .NET 引用? [英] How to detect a missing .NET reference at runtime?
问题描述
我的应用程序包含对外部库(SQL Server 管理对象)的引用.显然,如果运行时系统上不存在该库,只要没有调用使用该库中的类的方法,应用程序仍然可以运行.
My application contains references to an external library (the SQL Server Management Objects). Apparently, if the library is not present on the run-time system, the application still works as long as no methods are called that use classes from this library.
问题 1:这是指定的行为还是 CLR 加载库方式的(幸运的)副作用?
为了检测引用是否可访问,我目前使用这样的代码:
To detect whether the reference is accessible, I currently use code like this:
Function IsLibraryAvailable() As Boolean
Try
TestMethod()
Catch ex As FileNotFoundException
Return False
End Try
Return True
End Function
Sub TestMethod()
Dim srv As New Smo.Server() ' Try to create an object in the library
End Sub
它有效,但它似乎很丑陋.请注意,只有当 TestMethod 是一个单独的方法时才有效,否则将在 IsLibraryAvailable
的 beginning 抛出异常(在 try-catch 之前,即使对象实例化发生在 try-catch 块中).
It works, but it seems to be quite ugly. Note that it only works if TestMethod is a separate method, otherwise the exception will be thrown at the beginning of IsLibraryAvailable
(before the try-catch, even if the object instantiation occurrs within the try-catch block).
问题 2:有更好的选择吗?
特别是,我担心函数内联等优化可能会阻止我的代码工作.
In particular, I'm afraid that optimizations like function inlining could stop my code from working.
推荐答案
这是意料之中的,因为 JIT 在每个方法级别是惰性的.请注意,内联在这里不是问题,因为这也是 JIT 问题,而不是编译器问题.
That is expected, since the JIT is lazy at the per-method level. Note that inlining isn't an issue here, since that is also a JIT concern, not a compiler concern.
更好的选择:
- 确保应用已安装所需的一切
- 使用 ilmerge 或类似工具创建单个程序集(如果可能)
就我个人而言,我只会使用第一个选项.
Personally, I'd just use the first option.
这篇关于如何在运行时检测丢失的 .NET 引用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!