[LinqPad妙用]-在Net MVC中反射調用LinqPad中的Dump函數

來源:互聯網
上載者:User

標籤:des   style   blog   http   io   ar   color   使用   sp   

LinqPad有個非常強大的Dump函數。這篇講解一下如何將Dump函數應用在.Net MVC Web開發中。

先看效果:

  

 一、用.Net Reflector反編譯LinqPad.exe,找出Dump函數的定義:

  經過反編譯發現,Dump函數調用了LINQPad.ObjectGraph.Formatters.XhtmlWriter類中FormatObject函數,把對象轉成了Html。

 

 二、反射調用FormatObject函數:

  由於FormatObject函數是protect類型,不能直接調用,只能反射了。
  

 三、在.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函數

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.