反射生成数组

本文通过两个示例介绍如何使用C#中的反射机制获取方法信息并进行调用。第一个示例展示了如何使用GetMethod方法获取特定签名的方法信息;第二个示例则进一步演示了如何通过Invoke方法调用对象的方法。

看了下建哥的用反射生成的数组(http://blog.youkuaiyun.com/ojlovecd/archive/2008/11/11/3277766.aspx)

感觉不错,学习下,

(1)第一个例子是

public MethodInfo GetMethod(string name, Type[] types)

代码如下

using System; using System.Collections.Generic; using System.Text; using System.Reflection; namespace ConsoleApplication2 { class Method { public void MethodA(int i, int j) { } public void MethodA(int i) { } public void MethodA(ref int r) {} static void Main() { MethodInfo MInfo; //用GetMethod调用method类中Method(int i,int j)中的方法,new Type[] {...对应MethodA()方法中参数} MInfo = typeof(Method).GetMethod("MethodA", new Type[] { typeof(int),typeof(int)}); Console.WriteLine(MInfo.Name); MInfo = typeof(Method).GetMethod("MethodA", new Type[] {typeof(int) }); Console.WriteLine(MInfo.Name); MInfo = typeof(Method).GetMethod("MethodA", new Type[] { typeof(int).MakeByRefType() }); Console.WriteLine(MInfo.Name); } } }

第二个例子是

MethodBase..::.Invoke 方法 (Object, array<Object>[]()[])

代码如下

using System; using System.Collections.Generic; using System.Text; using System.Reflection; namespace ConsoleApplication2 { public class A { public void Area(int i, int j) { Console.WriteLine("Results:{0}", i * j); } } public class B { public void Min(int i, int j) { Console.WriteLine("Results:{0}", i + j); } } class InvokeInfo { static void Main() { A MyA = new A(); B MyB = new B(); Type TypeA = Type.GetType("ConsoleApplication2.A");//或者是Type TypeA = typeof(A); MethodInfo MethodInfoa = TypeA.GetMethod("Area"); Type TypeB = Type.GetType("ConsoleApplication2.B"); MethodInfo MethodInfob = TypeB.GetMethod("Min"); Console.WriteLine("Type Name:{0}{1}", TypeA.FullName, MethodInfoa.Invoke(MyA,new Object[] { 10, 12 })); Console.WriteLine("Type Name:{0}{1}", TypeB.FullName, MethodInfob.Invoke(MyB, new Object[] { 12, 13 })); } } }

其实GetMethod(string name, Type[] types)返回的是MethodInfo对象

代码一中

Method M = new Method(); MInfo = typeof(Method).GetMethod("MethodA", new Type[] { typeof(int), typeof(int) }); Console.WriteLine(MInfo.Name); //调用InVoke方法,Invoke(object obj,[] object param)第二个参数是一个对象数组 MInfo.Invoke(M, new Object[] { 3, 4 });

未完.....

没有时间......

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值