zoukankan      html  css  js  c++  java
  • .NET4 使用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);
                }
            }
        }
    }
  • 相关阅读:
    leetcode刷刷刷
    素数问题
    TCP/IP详解(整理)
    关于区块链应用方向与前景的一些思考
    设计模式
    面经中的各种问题汇总
    基于消逝时间量的共识机制(POET)
    c++语言知识点汇总
    二叉树前中后/层次遍历的递归与非递归形式(c++)
    layui表格搜索数据登录失效后的处理
  • 原文地址:https://www.cnblogs.com/jeriffe/p/2242197.html
Copyright © 2011-2022 走看看