一个非常简单的反射加速方案

不废话,直接上代码:

    class Program

    {

        private static readonly MethodInfo HelpMethod = typeof(Program).GetMethod("GetHelp", BindingFlags.NonPublic | BindingFlags.Static);



        static void Main(string[] args)

        {

            // you can cache the delegate, the type of delegate is always Func<object, object>

            var d = TestGet(typeof(Program).GetProperty("X"));

            var p = new Program { X = 1 };

            Console.WriteLine(d(p));

            Console.ReadLine();

        }



        private static Func<object, object> TestGet(PropertyInfo p)

        {

            var f = typeof(Func<,>).MakeGenericType(p.DeclaringType, p.PropertyType);

            var d = Delegate.CreateDelegate(f, p.GetGetMethod());

            return (Func<object, object>)Delegate.CreateDelegate(typeof(Func<object, object>), d, HelpMethod.MakeGenericMethod(p.DeclaringType, p.PropertyType));

        }



        private static object GetHelp<T, TResult>(Delegate d, object obj)

        {

            return ((Func<T, TResult>)d)((T)obj);

        }



        public int X { get; set; }

    }
View Code

 

你可能感兴趣的:(反射)