CSharp · Console
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
using VarDump;
using VarDump.CodeDom.Compiler;
using VarDump.Visitor;
// For more examples see https://github.com/ycherkes/VarDump/blob/main/test/VarDump.UnitTests/KnownObjectsSpec.cs
const string name = "World";
FormattableString str = $"Hello, {name}";
var options = new DumpOptions
{
ConfigureKnownObjects = (knownObjects, nextDepthVisitor, _, codeWriter) =>
{
knownObjects.Add(new FormattableStringVisitor(nextDepthVisitor, codeWriter));
}
};
var dumper = new CSharpDumper(options);
var result = dumper.Dump(str);
Console.WriteLine(result);
return;
class FormattableStringVisitor(INextDepthVisitor nextDepthVisitor, ICodeWriter codeWriter) : IKnownObjectVisitor
{
public string Id => nameof(FormattableString);
public bool IsSuitableFor(object obj, Type objectType)
{
return obj is FormattableString;
}
public void ConfigureOptions(Action<DumpOptions> configure)
{
}
public void Visit(object obj, Type objectType, VisitContext context)
{
var formattableString = (FormattableString)obj;
IEnumerable<Action> arguments =
[
() => codeWriter.WritePrimitive(formattableString.Format)
];
arguments = arguments.Concat(formattableString.GetArguments().Select(a => (Action)(() => nextDepthVisitor.Visit(a, context))));
codeWriter.WriteMethodInvoke(() =>
codeWriter.WriteMethodReference(
() => codeWriter.WriteType(typeof(FormattableStringFactory)),
nameof(FormattableStringFactory.Create)),
arguments);
}
}