首页 > 代码库 > C#.dynamic和反射

C#.dynamic和反射

using System;using System.Collections.Generic;using System.Diagnostics;using System.Linq;using System.Text;using System.Threading.Tasks;namespace dynamicDemo{    class Program    {        static void Main(string[] args)        {                      int times = 1000000;            DynamicSample reflectSample = new DynamicSample();            var addMethod = typeof(DynamicSample).GetMethod("Add");            Stopwatch watch1 = Stopwatch.StartNew();            for(var i = 0; i < times; i++)            {                addMethod.Invoke(reflectSample, new object[] { 1, 2 });            }            Console.WriteLine(string.Format("反射耗时:{0}毫秒",watch1.ElapsedMilliseconds));            //Display:反射耗时:630毫秒            dynamic dynamicSample = new DynamicSample();            Stopwatch watch2 = Stopwatch.StartNew();            for(var i = 0; i < times; i++)            {                dynamicSample.Add(1, 2);            }            Console.WriteLine(string.Format("dynamic 耗时:{0}毫秒",watch2.ElapsedMilliseconds));            //Display:dynamic耗时:89毫秒            DynamicSample reflectSampleBetter = new DynamicSample();            var addMethod2 = typeof(DynamicSample).GetMethod("Add");            var delg = (Func<DynamicSample,int,int,int>)Delegate.CreateDelegate(typeof(Func<DynamicSample,int, int, int>), addMethod2);            Stopwatch watch3 = Stopwatch.StartNew();            for(var i = 0; i < times; i++)            {                delg(reflectSampleBetter, 1, 2);            }            Console.WriteLine(string.Format("优化的反射耗时:{0}毫秒",watch3.ElapsedMilliseconds));            //Display:优化的反射耗时:17毫秒            Console.Read();        }    }    public class DynamicSample    {        public string Name { get; set; }        public int Add(int a,int b)        {            return a + b;        }    }}

没有优化的反射明显要比dynamic 效率低很多,优化后的反射效率是非常的理想的,但是牺牲了代码整洁.

dynamic和优化的反射是在一个数量级上.所以还是推荐使用dynamic来简化反射操作.

随着.net的升级反射性能也在提升.

测试环境是:.net4.5- vs2015.

C#.dynamic和反射