在C#中,您可以通过使用获得方法的名称

nameof(ISomeClass.SomeMethod)


这在F#中可行吗?当试图点入ISomeClass以获取SomeMethod时,它只是说“ SomeMethod不是静态方法”

最佳答案

您可以创建基于F#引用的方法,该方法以类型安全的方式检索接口方法。

open FSharp.Quotations
open FSharp.Quotations.Patterns

let getMethodName (e: Expr<'T -> 'U>) =
  match e with
  | Lambda (_, Call (_, mi, _)) -> mi.Name
  | _ -> failwith "%A is not a valid getMethodName expression, expected Lamba(_ Call(_, _, _))"

type ISomeInterface =
  interface
    abstract SomeMethod: unit -> unit
  end


[<EntryPoint>]
let main argv =
  let name = <@ fun (i : ISomeInterface) -> i.SomeMethod () @> |> getMethodName
  printfn "%s" name

  0

10-08 08:43
查看更多