简体   繁体   中英

Why does LinqPad run ToString() on some types when they are dumped?

I'm using NuGetVersion from the NuGet.Versioning package in LinqPad. I'm trying to Dump() it to inspect it's properties, but instead of the usual dump I just get the string representation.

For example, this:

var v = new NuGetVersion("1.0.0");
v.Dump();

Shows the following in the output window:

1.0.0

Does anyone know why LinqPad runs ToString() when some types are dumped, and how to change this behaviour?

In general, LINQPad calls ToString() rather than expanding the properties if the object implements System.IFormattable .

You could override this by writing an extension method in My Extensions that uses LINQPad's ICustomMemberProvider :

EDIT: There's now an easier way. Call LINQPad's Util.ToExpando() method:

var v = new NuGetVersion("1.0.0");
Util.ToExpando (v).Dump();

(Util.ToExpando converts the object into an ExpandoObject.)

For reference, here's the old solution that utilizes ICustomMemberProivder:

static class MyExtensions
{
    public static object ForceExpand<T> (this T value)
        => value == null ? null : new Expanded<T> (value);

    class Expanded<T> : ICustomMemberProvider
    {
        object _instance;
        PropertyInfo[] _props;

        public Expanded (object instance)
        {
            _instance = instance;
            _props = _instance.GetType().GetProperties();
        }

        public IEnumerable<string> GetNames() => _props.Select (p => p.Name);
        public IEnumerable<Type> GetTypes () => _props.Select (p => p.PropertyType);
        public IEnumerable<object> GetValues () => _props.Select (p => p.GetValue (_instance));
    }
}

Call it like this:

new NuGetVersion("1.2.3.4").ForceExpand().Dump();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM