开发者

How do I use the LINQPad Dump() extension method in Visual Studio? [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance. Closed 10 years ago.

LINQPad is amazing, and particularly useful is the Dump() extension methods which renders objects and structs of almost any type, anonymous or not, to the console.

Initially, when I moved to Visual Studio 2010, I tried to make my own Dump method using a delegate to get the values to render for anonymous types, etc. It's getting pretty 开发者_如何学编程complicated though and while it was fun and educational at first, I need a solid implementation. Having checked out the LINQPad code in .NET Reflector I am even more assured that I'm not going to get the implementation right.

Is there a free library I can include to provide the Dump functionality?


I wrote an extension method to Object that uses the Json.Net serializer with the pretty format option. JSON is easy enough to read when formatted like that. You miss type info, but I don't know that you need that, especially considering how easy this is. Hasn't failed me yet. I use Json.Net and not MS' because it has the capability of handling circular references in complex graphs, where MS' cannot, or didn't at the time I thought of it.

using Newtonsoft.Json;

public static class Dumper
{
    public static string ToPrettyString(this object value)
    {
         return JsonConvert.SerializeObject(value, Formatting.Indented);
    }

    public static T Dump<T>(this T value)
    {
        Console.WriteLine(value.ToPrettyString());
        return value;
    }
}


Look here (your path may vary):

C:\Program Files (x86)\Microsoft Visual Studio 10.0\Samples\1033\CSharpSamples.zip\LinqSamples\ObjectDumper


diceguyd30's answer is sourced from a discussion (especially Pat Kujawa's & anunay's comments) and describes how to call the LINQPad dump implementation from both C# and VB.NET:

public static string DumpToHtmlString<T>(this T objectToSerialize)
{
    string strHTML = "";
    try
    {
        var writer = LINQPad.Util.CreateXhtmlWriter(true);
        writer.Write(objectToSerialize);
        strHTML = writer.ToString();
    }
    catch (Exception exc)
    {
        Debug.Assert(false, "Investigate why ?" + exc);
    }
    return strHTML;
}


There's also a class library named ObjectDumper available as a NuGet package.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜