加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 从函数中提取函数名称

发布时间:2020-12-15 21:01:49 所属栏目:百科 来源:网络整理
导读:如何创建一个名为getFuncName的函数,它接受类型函数(unit – ’a)并返回其名称. 我正在与其中一个C#开发人员交谈,他们说你可以在Func类型上使用.Method属性,如示例here所示. 我试图将其转换为F#: 例如,将(单位 – ’a)转换为类型Func _然后在它上面调用属性
如何创建一个名为getFuncName的函数,它接受类型函数(unit – >’a)并返回其名称.

我正在与其中一个C#开发人员交谈,他们说你可以在Func类型上使用.Method属性,如示例here所示.

我试图将其转换为F#:

例如,将(单位 – >’a)转换为类型Func< _>然后在它上面调用属性,但它总是返回字符串“Invoke”.

let getFuncName f =
    let fFunc = System.Func<_>(fun _ -> f())
    fFunc.Method.Name

let customFunc() = 1.0

// Returns "Invoke" but I want it to return "customFunc"
getFuncName customFunc

这个问题的一些背景是:

我创建了一个类型的函数数组(unit – > Deedle.Frame).我现在想循环调用它们的那些函数并将它们保存到csv,其中csv名称与函数同名.一些假设代码如下:

let generators : (unit -> Frame<int,string>) array = ...

generators
|> Array.iter (fun generator -> generator().SaveCsv(sprintf "%s%s.csv" __SOURCE_DIRECTORY__ (getFuncName generator)))

这用于脚本意义而不是应用程序代码.

解决方法

不知道你是如何搜索信息的,但是对搜索引擎的第一个查询给了我这样的回复:

let getFuncName f =
   let type' = f.GetType()
   let method' = type'.GetMethods() |> Array.find (fun m -> m.Name="Invoke")

   let il = method'.GetMethodBody().GetILAsByteArray()
   let methodCodes = [byte OpCodes.Call.Value;byte OpCodes.Callvirt.Value]

   let position = il |> Array.findIndex(fun x -> methodCodes |> List.exists ((=)x))
   let metadataToken = BitConverter.ToInt32(il,position+1) 

   let actualMethod = type'.Module.ResolveMethod metadataToken
   actualMethod.Name

Unfortunately,this code only works when F# compiler does not inline function body into calling method.

取自here

虽然可能有一种更简单的方法.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读