不废话,直接上代码:

    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

 

posted on 2014-02-24 16:33  Zhenway  阅读(451)  评论(2编辑  收藏  举报