我正在用C# .net (2.0)写一个系统。它有一种可插拔模块的架构。可以将程序集添加到系统中,而无需重新生成基本模块。为了建立到新模块的连接,我希望尝试按名称调用其他模块中的静态方法。我不希望在构建时以任何方式引用被调用的模块。
在我编写非托管代码时,从.dll文件的路径开始,我会使用LoadLibrary()将.dll放入内存,然后使用get GetProcAddress()获取我希望调用的函数的指针。如何在C# / .NET中实现同样的效果。
发布于 2009-09-10 18:03:04
在使用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发布于 2009-09-10 18:07:55
下面是一个示例:
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 implementshttps://stackoverflow.com/questions/1406795
复制相似问题