使用委托优化反射
1. delegate
// 委托 public delegate int AddMethod(int a, int b); // 实现 var obj = new TestObject(); var objType = obj.GetType(); var add = objType.GetMethod("Add"); var d = (AddMethod)Delegate.CreateDelegate(typeof(AddMethod), obj, add); for (var i = 0; i < _TIMES; i++) d(a, b);
2. func
var d = (Func<TestObject, int, int, int>)Delegate.CreateDelegate(typeof(Func<TestObject, int, int, int>), add);
3. reflection
var obj = new TestObject(); var add = obj.GetType().GetMethod("Add"); for (var i = 0; i < _TIMES; i++) add.Invoke(obj, new object[] {a, b});
4. Test
private static double _Run(string description, Action<int, int> action, int a, int b) { if (action == null) throw new ArgumentNullException("action"); // 启动计时器 var stopwatch = Stopwatch.StartNew(); // 运行要测量的代码 action(a, b); // 终止计时 stopwatch.Stop(); // 输出结果 Console.WriteLine("{0}: {1}", description, stopwatch.Elapsed.TotalMilliseconds.ToString(CultureInfo.InvariantCulture)); // 返回执行时间 return stopwatch.Elapsed.TotalMilliseconds; }