我们如何在if条件语句中更改DLLImport属性中的程序集路径? 例如我想做这样的事情:
string serverName = GetServerName();
if (serverName == "LIVE")
{
DLLImportString = "ABC.dll";
}
else
{
DLLImportString = "EFG.dll";
}
DllImport[DLLImportString]
答案 0 :(得分:6)
您无法设置在运行时
期间计算的属性值您可以使用diff 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 dynamicaly[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();
答案 1 :(得分:4)
您需要通过LoadLibrary / GetProcAddress手动加载dll。
我对小应用程序有同样的需求并且使用了c ++ / cli。
在c#中,它看起来像:
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");
}
修改:Here是完整示例
答案 2 :(得分:1)
您可以使用条件编译来区分构建吗? 如果你可以/define构建服务器A,例如。使用/ define serverA进行编译,然后就可以了
#if serverA
DllImport["ABC.dll"]
#else
DllImport["EFG.dll"]
#endif