.NET4 使用dynamic简化反射的后期绑定

本文介绍如何在.NET4中利用dynamic关键字简化后期绑定,通过具体代码示例展示其应用,并对比原始反射方式,突出dynamic关键字在简化代码实现上的优势。

反射大家都不陌生,在NET4中引入了dynamic关键字,使用它可以简化后期绑定,这里我就不废话连篇了,直接上代码,直白的代码是最简单明了的诠释:

1.我们构建一个 Class Libary  命名为SimpleCaculator

2.在类库中构建类:

namespace SimpleCaculator
{
    public class SimpleMath
    {
        public int Add(int a, int b)
        {
            return a + b;
        }

        public int Sub(int a, int b)
        {
            return a - b;
        }
    }

3.构建Console Application 命名为:Dynamic-Reflect

4.编译SimpleCaculator 并且复制到Dynamic-Reflect项目的\bing\Debug目录下(如果你是Release构建,则复制到\bing\Release目录下)

5. Dynamic-Reflect的调用代码如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;

namespace Dynamic_Reflect
{
    class Program
    {
        static void Main(string[] args)
        {
           OriginalReflection();
           ReflectWithDynamic();
        }

        private static void OriginalReflection()
        {
            Assembly asm = Assembly.Load("SimpleCaculator");
            try
            {
                Type simpleMath = asm.GetType("SimpleCaculator.SimpleMath");
                object obj = Activator.CreateInstance(simpleMath);
                MethodInfo mi = simpleMath.GetMethod("Add");
                object[] args = { 2030 };

                Console.WriteLine("The Result of {0} + {1} is: {2} "2030, mi.Invoke(obj,args));
                Console.ReadKey();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }

        private static void ReflectWithDynamic()
        {
            Assembly asm = Assembly.Load("SimpleCaculator");
            try
            {
                Type simpleMath = asm.GetType("SimpleCaculator.SimpleMath");
                dynamic obj = Activator.CreateInstance(simpleMath);
                Console.WriteLine("The Result of {0} + {1} is: {2} "2030, obj.Add(2030));
                Console.ReadKey();
            }
            catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
    }
}

转载于:https://www.cnblogs.com/jeriffe/archive/2011/11/09/2242197.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值