4

参考在 F# 中是否有 C# 的 nameof(..) 的等价物?

对于以下情况,nameof 函数如何使用或扩展?

let nameof (q:Expr<_>) = 
    match q with 
    | Patterns.Let(_, _, DerivedPatterns.Lambdas(_, Patterns.Call(_, mi, _))) -> mi.Name
    | Patterns.PropertyGet(_, mi, _) -> mi.Name
    | DerivedPatterns.Lambdas(_, Patterns.Call(_, mi, _)) -> mi.Name
    | _ -> failwith "Unexpected format"

let any<'R> : 'R = failwith "!"

let s = _nameof <@ System.Char.IsControl @> //OK

type A<'a>() = 
    static member MethodWith2Pars(guid:Guid, str:string) = ""
    static member MethodWith2Pars(guid:Guid, ba:byte[]) = ""

let s1 = nameof <@ A<_>.MethodWith2Pars @> //Error  FS0503  A member or object constructor 'MethodWith2Pars' taking 1 arguments is not accessible from this code location. All accessible versions of method 'MethodWith2Pars' take 2 arguments
let s2 = nameof <@ A<_>.MethodWith2Pars : Guid * string -> string @> //Same error

编译器给出以下错误:

错误 FS0503 无法从此代码位置访问采用 1 个参数的成员或对象构造函数“MethodWith2Pars”。方法“MethodWith2Pars”的所有可访问版本都采用 2 个参数

4

2 回答 2

6

您链接的答案有点过时了。F# 5.0(最近发布)提供了真正的nameof功能。查看公告:https ://devblogs.microsoft.com/dotnet/announcing-f-4-7/#nameof

自 F# 4.7 起,此功能也存在于预览版中:https ://devblogs.microsoft.com/dotnet/announcing-f-4-7/#nameof

于 2020-12-03T03:27:04.630 回答
3

您可以这样编写代码:

open System

type A() = 
    static member MethodWith2Pars(guid:Guid, str:string) = ""
    static member MethodWith2Pars(guid:Guid, ba:byte[]) = ""

let s1 = nameof (A.MethodWith2Pars : Guid * byte[] -> string)
let s2 = nameof (A.MethodWith2Pars : Guid * string -> string)

由于重载,需要类型注释。不知道为什么类声明中有一个泛型类型参数,但它没有在任何地方使用,所以我只是删除了它。

于 2020-12-03T06:05:52.037 回答