.net 运行时将按需 JIT 您的代码。这就是您完成此任务的方式。
如果您依赖依赖于可能存在或不存在的 DLL 函数的代码的延迟实例化。您可以使用GetProcAddress 函数来检查该函数。如果我们正在编写好的旧 Win32 代码,我们会这样做。
这是 Jon Skeet 的 article 关于懒惰的一个简单示例:
public sealed class Singleton
{
[DllImport("kernel32", CharSet=CharSet.Ansi, ExactSpelling=true, SetLastError=true)]
private static extern IntPtr GetProcAddress(IntPtr hModule, string procName);
[DllImport("kernel32.dll", CharSet=CharSet.Auto)]
private static extern IntPtr GetModuleHandle(string lpModuleName);
public bool IsQueryFullProcessImageNameSupported { get; private set; }
public string QueryFullProcessImageName(IntrPtr handle)
{
if (!IsQueryFullProcessImageNameSupported) {
throw new Exception("Does not compute!");
}
int capacity = 1024;
var sb = new StringBuilder(capacity);
Nested.QueryFullProcessImageName(handle, 0, sb, ref capacity);
return sb.ToString(0, capacity);
}
private Singleton()
{
// You can use the trick suggested by @leppie to check for the method
// or do it like this. However you need to ensure that the module
// is loaded for GetModuleHandle to work, otherwise see LoadLibrary
IntPtr m = GetModuleHandle("kernel32.dll");
if (GetProcAddress(m, "QueryFullProcessImageNameW") != IntrPtr.Zero)
{
IsQueryFullProcessImageNameSupported = true;
}
}
public static Singleton Instance { get { return Nested.instance; } }
private class Nested
{
// Explicit static constructor to tell C# compiler
// not to mark type as beforefieldinit
static Nested()
{
// Code here will only ever run if you access the type.
}
[DllImport("kernel32.dll", SetLastError=true)]
public static extern bool QueryFullProcessImageName([In]IntPtr hProcess, [In]int dwFlags, [Out]StringBuilder lpExeName, ref int lpdwSize);
public static readonly Singleton instance = new Singleton();
}
}
这里的懒惰是JITting继承的,其实没必要。但是,它确实允许我们保持一致的命名约定。