Is it possible to use CallerMemberNameAttribute in f#

后端 未结 2 682
情书的邮戳
情书的邮戳 2020-12-17 17:02

The attribute and C# examples are noted here but it doesn\'t look to be possible for FSharp.

http://msdn.microsoft.com/en-us/library/system.runtime.compilerservices.

相关标签:
2条回答
  • 2020-12-17 17:10

    Here's a quick 'n' dirty hack, which abuses inline to get this info:

    module Tracing = 
        open System
        open System.Text.RegularExpressions
    
        let (|TraceInfo|_|) (s:string) =
            let m = Regex.Match(s, "at (?<mem>.+?) in (?<file>.+?\.[a-zA-Z]+):line (?<line>\d+)")
            if m.Success then
                Some(m.Groups.["mem"].Value, m.Groups.["file"].Value, int m.Groups.["line"].Value)
            else None
    
        let inline trace s =
            printfn "%s" s
            match Environment.StackTrace with
            | TraceInfo(m, f, l) ->
                printfn "  Member: %s" m
                printfn "  File  : %s" f
                printfn "  Line  : %d" l
            | _ -> ()
    

    It actually does work, more or less:

    enter image description here enter image description here

    0 讨论(0)
  • 2020-12-17 17:30

    A quick search through the compiler source code shows that the name CallerMemberName does not appear anywhere in the code, so I think this feature is not supported. (You can certainly mark a parameter with the attribute, but these attributes are special - they instruct the compiler instead of being discovered and used in some way at runtime.)

    Update July 2016: As of late June, F# now supports CallerLineNumber and CallerFilePath, but CallerMemberName is still absent. It seems like that one in particular is more difficult to implement, unfortunately.

    On a related note, F# has a few special identifiers that let you get the current source file name and line number, so you might be able to get similar information with __SOURCE_DIRECTORY__ and __LINE__
    (but not from the caller as in C#).

    0 讨论(0)
提交回复
热议问题