C # dynamic method call

Source: Internet
Author: User
Dynamic Dynamic Method Invocation

One very useful feature related to Reflection are the ability to create objects dynamically and call methods on them.
Note:Class1.cs has methods which'll be dynamically invoked in runtime from the DynaInvoke.cs

Class1.cs

Using System;
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;
}
}
Save this file as Class1.cs and Compile c:/>csc/t:library Class1.cs

DynaInvoke.cs

Using System;
Using System.Reflection;
Class DynamicInvoke
{
public static void Main (String [] args)
{

String Path = "Class1.dll"
Assembly a = assembly.load (path);

Invoking a static method
Type mm = A.gettype ("Class1");
String i = (string) mm. InvokeMember ("Method1", Bindingflags.default | Bindingflags.invokemethod,null,null,new Object [] {}); Console.WriteLine (i);

Invoking a Non-static method
Object o = activator.createinstance (mm);
i = (String) mm. InvokeMember ("Method2", Bindingflags.default | Bindingflags.invokemethod,null,o,new Object [] {});
Console.WriteLine (i);

Invoking a non-static method with parameters
Object [] par = new object[] {"Kunal"};
i = (String) mm. InvokeMember ("Method3", Bindingflags.default | BINDINGFLAGS.INVOKEMETHOD,NULL,O,PAR);
Console.WriteLine (i);
}
}

Save this file as DynaInvoke.cs and Compile C:/>CSC DynaInvoke.cs and run C:\>dynainvoke


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.