我正在用C#.net(2.0)编写一个系统。它具有可插拔模块的架构。可以将程序集添加到系统中,而无需重建基础模块。为了建立与新模块的连接,我希望尝试按名称在其他模块中调用静态方法。我不希望在构建时以任何方式引用被调用的模块。
当我从.dll文件的路径开始编写非托管代码时,我会使用LoadLibrary()将.dll放入内存,然后使用get GetProcAddress()获取指向我希望调用的函数的指针。如何在C#/ .NET中实现相同的结果。
答案 0 :(得分:16)
使用Assembly.LoadFrom(...)加载程序集后,您可以按名称获取类型并获取任何静态方法:
Type t = Type.GetType(className);
// get the method
MethodInfo method = t.GetMethod("MyStaticMethod",BindingFlags.Public|BindingFlags.Static);
Then you call the method:
method.Invoke(null,null); // assuming it doesn't take parameters
答案 1 :(得分:1)
这是一个样本:
string assmSpec = ""; // OS PathName to assembly name...
if (!File.Exists(assmSpec))
throw new DataImportException(string.Format(
"Assembly [{0}] cannot be located.", assmSpec));
// -------------------------------------------
Assembly dA;
try { dA = Assembly.LoadFrom(assmSpec); }
catch(FileNotFoundException nfX)
{ throw new DataImportException(string.Format(
"Assembly [{0}] cannot be located.", assmSpec),
nfX); }
// -------------------------------------------
// Now here you have to instantiate the class
// in the assembly by a string classname
IImportData iImp = (IImportData)dA.CreateInstance
([Some string value for class Name]);
if (iImp == null)
throw new DataImportException(
string.Format("Unable to instantiate {0} from {1}",
dataImporter.ClassName, dataImporter.AssemblyName));
// -------------------------------------------
iImp.Process(); // Here you call method on interface that the class implements