如何在运行时调用C#静态方法而无需在编译时引用?

6
我正在使用C# .NET(2.0)编写一个系统。它具有可插入模块的架构。可以在不重新构建基本模块的情况下向系统添加程序集。为了连接到新模块,我希望尝试通过名称调用其他模块中的静态方法。我不想在构建时引用所调用的模块。
当我编写非托管代码时,从.dll文件路径开始,我会使用LoadLibrary()将.dll加载到内存中,然后使用GetProcAddress()获取指向所需函数的指针。在C# / .NET中如何实现相同的结果?
2个回答

18
使用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

2
+1,另外值得一提的是,“className”还必须包含命名空间,例如“MyNamespace.Class1”。 - icl7126

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

调用实例方法的代码。我要求的是静态方法。但是,最终我还是需要这个片段。谢谢。+1 - Rodney Schuler

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接