码迷,mamicode.com
首页 > Web开发 > 详细

[LinqPad妙用]-在Net MVC中反射调用LinqPad中的Dump函数

时间:2014-12-04 23:05:09      阅读:254      评论:0      收藏:0      [点我收藏+]

标签:des   style   blog   http   io   ar   color   使用   sp   

LinqPad有个非常强大的Dump函数。这篇讲解一下如何将Dump函数应用在.Net MVC Web开发中。

先看效果:

bubuko.com,布布扣

  

 一、用.Net Reflector反编译LinqPad.exe,找出Dump函数的定义:

  经过反编译发现,Dump函数调用了LINQPad.ObjectGraph.Formatters.XhtmlWriter类中FormatObject函数,把对象转成了Html。

bubuko.com,布布扣

 

 二、反射调用FormatObject函数:

  由于FormatObject函数是protect类型,不能直接调用,只能反射了。
  bubuko.com,布布扣

 三、在.Net MVC中使用Dump:

 BigDump.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using System.Reflection;
using System.IO;
using System.Text;

namespace System.Web
{
    public static class BigDump
    {
        private static MethodInfo dumpMethodInfo = null;
        private static object xhtmlWriterInstance = null;
        private static void Init()
        {
            if (dumpMethodInfo == null || xhtmlWriterInstance == null)
            {
                var asm = Assembly.LoadFile(HttpContext.Current.Server.MapPath("~/Lib/LINQPad.exe"));
                Type t1 = asm.GetType("LINQPad.ObjectGraph.Formatters.XhtmlWriter");
                ConstructorInfo t1Constructor = t1.GetConstructor(new Type[] { typeof(TextWriter), typeof(bool) });
                xhtmlWriterInstance = t1Constructor.Invoke(new Object[] { new StringWriter(new StringBuilder()), false });
                dumpMethodInfo = t1.GetMethod("FormatObject", BindingFlags.Instance | BindingFlags.NonPublic);
            }
        }
        public static MvcHtmlString Render<T>(this T o, string description = "", int? depth = 3)
        {
            Init();
            var result = dumpMethodInfo.Invoke(xhtmlWriterInstance, new Object[] { o, description, depth, new TimeSpan() });
            return new MvcHtmlString(result as string);
        }

        public static List<MvcHtmlString> Stack { get; set; }
        static BigDump()
        {
            Stack = new List<MvcHtmlString>();
        }
        public static T Dump<T>(this T o, string description = "", int? depth = 3)
        {
            Stack.Add(o.Render(description, depth));
            return o;
        }
        public static void Clear()
        {
            Stack = new List<MvcHtmlString>();
        }
        public static MvcHtmlString Flush()
        {
            var html = new MvcHtmlString(string.Join("\r\n", Stack.Select(r => r.ToHtmlString()).ToArray()));
            Clear();
            return html;

        }
    }
}

[LinqPad妙用]-在Net MVC中反射调用LinqPad中的Dump函数

标签:des   style   blog   http   io   ar   color   使用   sp   

原文地址:http://www.cnblogs.com/linqpad/p/4143824.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!