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)); dynamic dynamicSample = new DynamicSample(); Stopwatch watch2 = Stopwatch.StartNew(); for (int i = 0; i < times; i++) { dynamicSample.Add(1, 2); } Console.WriteLine(string.Format("dynamic耗时:{0} 毫秒", watch2.ElapsedMilliseconds)); 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)); Console.Read(); }
static void Main(string[] args) { Console.WriteLine("Hello World!"); var times = 1000000; DynamicSample dynamicSample = new DynamicSample(); var addMethod = typeof(DynamicSample).GetMethod("Add"); var delg = (Func <DynamicSample, int, int, int>)Delegate.CreateDelegate( typeof(Func <DynamicSample, int, int, int>), addMethod); Stopwatch stopwatch1 = Stopwatch.StartNew(); for (int i = 0; i < times; i++) { //addMethod.Invoke(dynamicSample, new object?[] { 1, 2 }); delg(dynamicSample, 1, 2); } Console.WriteLine($"反射耗时:{stopwatch1.ElapsedMilliseconds}毫秒"); dynamic dynamicSample2 = new DynamicSample(); Stopwatch stopwatch2 = Stopwatch.StartNew(); for (int i = 0; i < times; i++) { dynamicSample2.Add(4, 2); } Console.WriteLine($"dynamic耗时:{stopwatch2.ElapsedMilliseconds}毫秒"); }