Accessing class and function after compiling ( CompiledAssembly )

╄→尐↘猪︶ㄣ 提交于 2019-12-08 07:14:55

问题


Heres some example code. I successfully figured out how to compile this. I grabbed the location and was able to use visual studios object browser to look through the DLL. I cant figure out how to get a class instance and call a function.

    public static void test()
    {
        JScriptCodeProvider js = new JScriptCodeProvider();
        System.CodeDom.Compiler.CompilerParameters param = new System.CodeDom.Compiler.CompilerParameters();
        var cr = js.CompileAssemblyFromSource(param, new string[] { "package pkg { class b { public function increment(x) { return x+1; } } }" });
        foreach (var e in cr.Errors) { 
            var s = e.ToString(); 
        }
        var asm = cr.CompiledAssembly;
        var module = cr.CompiledAssembly.GetModules();
//or var module = cr.CompiledAssembly.GetModule("JScript Module");
        //...
    }

回答1:


Hmmm realy late on the answer but this is how you would invoke a method from a CodeDom compiled class

You have to use reflection to create an assembly from your compiler results...(your var cr)

Assembly assembly = cr.CompiledAssembly;

Then you have to create an instance of the class you want

object sourceClass = assembly.CreateInstance("YourNamespace.YourClass");

Then you invoke any method inside the class

var result = sourceClass.GetType().InvokeMember("YourMethod", BindingFlags.InvokeMethod, null, sourceClass, new object[] { *Parameters go here* });

And with that what ever the method you invoked had to returned would now be the value of the "result" var....pretty easy.



来源:https://stackoverflow.com/questions/1698870/accessing-class-and-function-after-compiling-compiledassembly

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!