C#反射(简单例子)

反射(Reflection)是.NET中的重要机制,通过反射,可以在运行时获得.NET中每一个类型(包括类、结构、委托、接口和枚举等)的成员,包括方法、属性、事件,以及构造函数等。还可以获得每个成员的名称、限定符和参数等。有了反射,即可对每一个类型了如指掌。如果获得了构造函数的信息,即可直接创建对象,即使这个对象的类型在编译时还不知道。 

 class Program
    {
        /// <summary>
        /// 创建Mymath类库,包含静态方法Add和非静态方法Abstract,使用loadFile来加载
        /// </summary>
        /// <param name="args"></param>
        static void Main(string[] args)
        {
            //加载程序集
            Assembly assem = Assembly.LoadFile(@"D:\我的文档\Visual Studio 2008\Projects\MyMath\MyMath\bin\Debug\MyMath.dll");
            Type type = assem.GetType("MyMath.Math");
            //利用MethodInfo得到方法的具体信息
            MethodInfo method = type.GetMethod("Add");
            Console.WriteLine(method.ToString());


            //调用静态方法Add
            object[] parameters = new object[2];
            parameters[0] = 1; parameters[1] = 2;
            string result = (string)method.Invoke(null, parameters);
            Console.WriteLine("the add result is {0}", result);           




            //使用非静态方法Abstract
            Object obj = assem.CreateInstance("MyMath.Math");
            //接着是调用自己指定的Abstract方法
            method = type.GetMethod("Abstract");
            //传入参数列表和调用的对象
            result = (string)method.Invoke(obj, parameters);
            Console.WriteLine("the abstract result is {0}", result); 
            Console.ReadKey(); 
        }
    }

namespace MyMath
{
    public class Math
    {
        public static string Add(double num1,double num2)
        {
            double result = num1 + num2;
            return result.ToString();
        }

        public string Abstract(double num1, double num2)
        {
            double result = num1 - num2;
            return result.ToString();
        }
    }
}

返回结果:

System.String Add(Double, Double)

the add result is 3

the abstract result is -1




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值