C # dynamic method call

Source: Internet
Author: User

This article describes how C # dynamically invokes methods at run time. When certain types are run-time dynamic, the static encoding at compile time cannot resolve the method calls of these dynamic objects or classes. This article gives you a sword to make it possible for the method call of the dynamic object.

1. Dynamic invocation of methods in DLLs

<summary>///This class will be individually programmed into Class1.dll assembly///</summary> class Class1 {public static string method1 () {
    Return "I am Static Method (method1) in Class1";
    public string Method2 () {return "I am-a Instance method (METHOD2) in Class1";
    public string method3 (string s) {return "Hello" + S; }///<summary>///This class is placed separately into the Test.exe assembly///</summary> class DynamicInvoke {public static void Main (Strin
        G[] args {//dynamically loading assembly string path = "Class1.dll";

        Assembly Assembly = assembly.load (path); Gets type Type type = assembly based on the type name.

        GetType ("Class1"); 1. Dynamically invoke static method String str = (string) type based on method name. InvokeMember ("Method1", Bindingflags.default |
        BindingFlags.InvokeMethod, NULL, NULL, new object[] {});

        Console.WriteLine (str);
        2. Dynamically invoke the member method of a dynamic object based on the method name object o = Activator.CreateInstance (type); str = (string) type. InvokeMember ("MeThod2 ", Bindingflags.default |
        BindingFlags.InvokeMethod, NULL, O, new object[] {});

        Console.WriteLine (str);
        3. Dynamically invoke the active object's parametric member method according to the method name object[] par = new object[] {"Kunal"}; str = (string) type. InvokeMember ("Method3", Bindingflags.default |
        BindingFlags.InvokeMethod, NULL, O, par);

        Console.WriteLine (str); Invocation of the public static bool TryParse (string s, out int result) method in InvokeMember//System.Int32 with out decoration var a rguments = new object[] {str, NULL}; Note that only the parameters can be written out here, and the out parameter is null and does not have a relationship typeof (int). InvokeMember ("TryParse", System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.InvokeMethod |
        System.Reflection.BindingFlags.Static, NULL, NULL, arguments);
    Console.WriteLine (Arguments[1]); }
}

2. Dynamically load class files and Invoke methods:

Using System;
Using System.CodeDom.Compiler;
Using System.IO;
Using System.Reflection;
Using System.Threading;
Using System.Windows.Forms;

Using Microsoft.csharp;
        namespace _32.dynamicreflection {Internal class program {private static void Main (string[] args)
            {#region built-in tagging method (dynamically loaded) const string className = "dynamicreflection.test";//class name must be full String fileName =Thread.getdomain (). BaseDirectory + "Test.cs";

            if (file.exists (filename)) {var sourcefile = new FileInfo (filename);
                CodeDomProvider Provider = new CSharpCodeProvider ();
                var cp = new CompilerParameters (); Cp. Referencedassemblies.add ("System.dll"); Add namespace reference CP. GenerateExecutable = false; Generate Class library CP. GenerateInMemory = true; Save to memory CP. TreatWarningsAsErrors = false; Do not compile warnings as error//compile CompilerResults CR = provider.
                Compileassemblyfromfile (CP, Sourcefile.fullname); if (CR. Errors.Count < 1) {Assembly asm = cr. compiledassembly; Load//1. Call the static method type type = ASM.
                    GetType (ClassName); var str = (string) type. InvokeMember ("SayHello1", Bindingflags.default |
                    BindingFlags.InvokeMethod, NULL, NULL, new object[] {}); Console.WriteLine (str); 2. Invoke instance Method object instance = asm.
                    CreateInstance (ClassName); str = (string) type. InvokeMember ("SayHello2", Bindingflags.default |
                    BindingFlags.InvokeMethod, NULL, Instance,new object[] {});

                    Console.WriteLine (str);
                    3. Invoke the method with the parameter var par = new object[] {"zhangqs008"}; str = (string) type. InvokeMember ("SayHello3", Bindingflags.default |
                    BindingFlags.InvokeMethod, NULL, INSTANCE,PAR);

                    Console.WriteLine (str);
                Console.read ();
                    else {string msg = null; for (int index = 0; index < CR. Errors.Count; index++) {CompilerError error = Cr.
                        Errors[index];
                        MSG + + "error" + (index + 1) + "" "+ Environment.NewLine; msg + + "[file]" + error. FileName + Environment.NewLine; msg + = "[position] line" + error. Line + ", column" + Error.
                        Column + Environment.NewLine; msg + + "[INFO]" + error.
                        ErrorText + Environment.NewLine;
                    msg + Environment.NewLine;
                MessageBox.Show (MSG, "Built-in method class compilation error"); }} #endregion}}}
class file:

Namespace Dynamicreflection
{public
    class Test
    {public
        static string SayHello1 ()
        {return
            " Hello static method ";
        }

        public string SayHello2 ()
        {return
            ' Hello instance method ';
        }

        public string SayHello3 (string args)
        {return
            "Hello args" + args;
        }
    }
}



Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.