C#动态方法调用

Dynamic Method Invocation

One very useful feature related to Reflection is the ability to create objects dynamically and call methods on them.
note : Class1.cs has methods which will be dynamically invoked at 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 
 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值