如何在if条件语句内更改DLLImport属性中的程序集路径? 例如,我想要做这样的事情:
string serverName = GetServerName();
if (serverName == "LIVE")
{
DLLImportString = "ABC.dll";
}
else
{
DLLImportString = "EFG.dll";
}
DllImport[DLLImportString]
您不能设置在运行时计算的属性值。
您可以使用不同的DllImports
定义两个方法,并在if语句中调用它们。
DllImport["ABC.dll"]
public static extern void CallABCMethod();
DllImport["EFG.dll"]
public static extern void CallEFGMethod();
string serverName = GetServerName();
if (serverName == "LIVE")
{
CallABCMethod();
}
else
{
CallEFGMethod();
}
或者您可以尝试使用winapi的LoadLibrary动态加载dll。
[DllImport("kernel32.dll", EntryPoint = "LoadLibrary")]
static extern int LoadLibrary([MarshalAs(UnmanagedType.LPStr)] string lpLibFileName);
[DllImport("kernel32.dll", EntryPoint = "GetProcAddress")]
static extern IntPtr GetProcAddress( int hModule,[MarshalAs(UnmanagedType.LPStr)] string lpProcName);
[DllImport("kernel32.dll", EntryPoint = "FreeLibrary")]
static extern bool FreeLibrary(int hModule);
创建适合dll中方法的委托
delegate void CallMethod();
int hModule = LoadLibrary(path_to_your_dll); // you can build it dynamically
if (hModule == 0) return;
IntPtr intPtr = GetProcAddress(hModule, method_name);
CallMethod action = (CallMethod)Marshal.GetDelegateForFunctionPointer(intPtr, typeof(CallMethod));
action.Invoke();
delegate int MyFunc(int arg1, [MarshalAs(UnmanagedType.LPStr)]String arg2);
public static void Main(String[] args)
{
IntPtr mydll = LoadLibrary("mydll.dll");
IntPtr procaddr = GetProcAddress(mydll, "Somfunction");
MyFunc myfunc = Marshal.GetDelegateForFunctionPointer(procaddr, typeof(MyFunc));
myfunc(1, "txt");
}
编辑:这里是完整的示例。