Can StructuredFormatDisplayAttribute be used as part of an extension method

I don't think this is possible, but can you do something similar to this to allow custom formatting through a type extension?

[<StructuredFormatDisplayAttribute("Rate: {PrettyPrinter}")>] type Rate with member x.PrettyPrinter = x.Title + string x.Value 

Note. It looks like an internal extension (the same assembly), but not as an additional extension.

If I don’t think it could be a function request, if someone doesn’t have a good alternative?

+4
source share
2 answers

No, It is Immpossible. In FSI, you can use fsi.AddPrinter to configure output.

 fsi.AddPrinter (fun (x: Rate) -> x.Title + string x.Value) 

EDIT

For general line formatting, you can use Printf with the %a format specifier. Several additional features can make this more convenient.

 [<CompilationRepresentation(CompilationRepresentationFlags.ModuleSuffix)>] module Rate = let stringify (x: Rate) = x.Title + string x.Value let print rate = printf "%s" (stringify rate) printf "Rate: %a" (fun _ -> Rate.print) rate let formattedString = sprintf "Rate: %a" (fun _ -> Rate.stringify) rate 
+2
source

As you say, StructuredFormatDisplayAttribute only works for members that are compiled as properties (including standard properties, same assemblies, but not extensions). Under the cover, it is accessed using reflection (as you can see, it can also be private):

 let getProperty (obj: obj) name = let ty = obj.GetType() ty.InvokeMember(name, (BindingFlags.GetProperty ||| BindingFlags.Instance ||| BindingFlags.Public ||| BindingFlags.NonPublic), null, obj, [| |],CultureInfo.InvariantCulture) 

If you need this for debugging purposes, the DebuggerTypeProxy attribute may be an alternative (see the MSDN documentation ). This allows you to replace the original type with a proxy type, which is used to display the type in the debugger. (But I think that the attribute should still be placed in the actual type definition, and not on the extension.)

+2
source

Source: https://habr.com/ru/post/1437383/


All Articles