Reflection 如何获取F#中函数参数的名称?

Reflection 如何获取F#中函数参数的名称?,reflection,f#,Reflection,F#,我可以写一个返回作为参数给出的函数名的函数吗 let funName f: string = // returns the name of f. 例如,如果我将printfn作为参数传递给funName,它将返回“printfn” 编辑:我想编写一个函数doc,它返回与给定函数关联的XML文档 let doc f = // returns the XML documentation of the function `f`. 要使用类似的方法检索函数的摘要,我想知道函数的名称。我无法想象

我可以写一个返回作为参数给出的函数名的函数吗

let funName f: string =
   // returns the name of f.
例如,如果我将
printfn
作为参数传递给funName,它将返回“printfn”

编辑:我想编写一个函数
doc
,它返回与给定函数关联的XML文档

let doc f = // returns the XML documentation of the function `f`.

要使用类似的方法检索函数的摘要,我想知道函数的名称。

我无法想象您为什么要这样做,我不认为有一种方法可以通过反射来实现这一点,但可能会让您半途而废

let doc f = // returns the XML documentation of the function `f`.
open Microsoft.FSharp.Quotations

let rec funName = function
| Patterns.Call(None, methodInfo, _) -> methodInfo.Name
| Patterns.Lambda(_, expr) -> funName expr
| _ -> failwith "Unexpected input"

let foo () = 42
funName <@ foo @>       // "foo"
打开Microsoft.FSharp.quotes
让rec funName=函数
|Patterns.Call(None,methodInfo,824;)->methodInfo.Name
|Patterns.Lambda(u,expr)->funName expr
|_u824;->故障与“意外输入”
设foo()=42
funName/“foo”
但请注意,某些预定义的库函数具有不同的内部名称

funName <@ printfn @>   // "PrintFormatLine"
funName <@ id @>        // "Identity"
funName//“PrintFormatLine”
funName/“标识”
请注意,从F#4.0开始,类类型可以自动引用其参数,与用户的答案相比,简化了调用站点:

open Microsoft.FSharp.Quotations

type DocumentGetter =
    static member GetName([<ReflectedDefinition>]x:Expr<_->_>) = 
        match x with
        | DerivedPatterns.Lambdas(_, Patterns.Call(_,methodInfo,_)) ->
            methodInfo.Name

let f x y = x + y

DocumentGetter.GetName f
打开Microsoft.FSharp.quotes
类型文档获取器=
静态成员GetName([]x:Expr>)=
将x与
|DerivedPatterns.Lambdas(_,Patterns.Call(_,methodInfo,_))->
methodInfo.Name
设f x y=x+y
DocumentGetter.GetName f

你到底想在这里实现什么——用咖喱煮东西可能会很复杂。也许类似于?OP可能已经看到了这一点,但我要补充一点(参见Nikon的第三条评论)。我经常遇到的一个使用类似东西的用例是在实现
INotifyPropertyChanged
时。我绝对不喜欢返回字符串。另一个用例是代码生成。例如,今天我想创建一个Rust静态数组,我的F#code中已经有了这个数组。数组中的结构包含函数指针。我没有使用Rust语法再次键入整个表,而是编写了一个脚本,但必须找到结构中引用的函数的名称。不要质疑人们的用例;)