反射大家都不陌生,在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);
            }
        }
    }
}

相关文章:

  • 2022-12-23
  • 2021-06-06
  • 2021-11-23
  • 2022-01-30
  • 2022-12-23
  • 2022-12-23
  • 2021-08-29
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2022-02-11
  • 2022-12-23
  • 2022-12-23
  • 2021-07-12
  • 2021-07-08
  • 2021-06-24
相关资源
相似解决方案