C# call a static method at runtime without a build time reference?

Rod*_*ler 6 .net c# .net-2.0

I am writing a system in C# .net (2.0). It has a pluggable module sort of architecture. Assemblies can be added to the system without rebuilding the base modules. To make a connection to the new module, I wish to attempt to call a static method in some other module by name. I do not want the called module to be referenced in any manner at build time.

Back when I was writing unmanaged code starting from the path to the .dll file I would use LoadLibrary() to get the .dll into memory then use get GetProcAddress() get a pointer to the function I wished to call. How do I achieve the same result in C# / .NET.

Phi*_*ert 17

使用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
Run Code Online (Sandbox Code Playgroud)

  • +1,还值得一提的是'className'还必须包含名称空间,如"MyNamespace.Class1" (2认同)