Getting return values from codedom results's method

684 views Asked by At

i have compiled .cs file using codedom and extract its method through invokemember. but how can i get a value from that method? for example: i want to get webcontrol that has been created in the method

here's my code

    string[] filepath = new string[1];
        filepath[0] = @"C:\Users\xxxx\Documents\Visual Studio 2010\Projects\xxx\xx\invokerteks.cs";

        CodeDomProvider cpd = new CSharpCodeProvider();
        CompilerParameters cp = new CompilerParameters();
        cp.ReferencedAssemblies.Add("System.dll");
        cp.ReferencedAssemblies.Add("System.Web.dll");
        cp.GenerateExecutable = false;
        CompilerResults cr = cpd.CompileAssemblyFromFile(cp, filepath);

        if (true == cr.Errors.HasErrors)
        {
            System.Text.StringBuilder sb = new System.Text.StringBuilder();
            foreach (System.CodeDom.Compiler.CompilerError ce in cr.Errors)
            {
                sb.Append(ce.ToString());
                sb.Append(System.Environment.NewLine);
            }
            throw new Exception(sb.ToString());
        }

        Assembly invokerAssm = cr.CompiledAssembly;
        Type invokerType = invokerAssm.GetType("dynamic.hello");
        object invokerInstance = Activator.CreateInstance(invokerType);

        invokerType.InvokeMember("helloworld", BindingFlags.InvokeMethod | BindingFlags.Instance | BindingFlags.NonPublic, null, invokerInstance, null);

and here's my invokerteks.cs

    namespace dinamis
    {
public class halo
{
    private void halodunia()
    {
        System.Console.WriteLine("Hello World!!");

    }
}

}

can you provide me a links tutorial for this issue?

1

There are 1 answers

0
Isaac Hildebrandt On BEST ANSWER

InvokeMember will return whatever is returned by the method. Since your helloworld method has void as it's return, nothing will be returned. In order to get something out, define your return type and invoke as usual:

public class Hello
{
    private int helloworld()
    { 
        return new Random().NextInt();
    }
}

Which can be called like:

var type = typeof(Hello);
int value = (int)type.InvokeMember("helloworld", BindingFlags.InvokeMethod | BindingFlags.Instance | BindingFlags.NonPublic, null, invokerInstance, null);

InvokeMember always returns and instance of object so you have to cast to your desired type. Be careful for invalid casts here.