续“在F#中是否有等效于C#的nameof(..)?”
f#
参考在 F# 中是否有等效于 C# 的 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 个参数
回答
您链接的答案有点过时了。F# 5.0(最近发布)提供了真正的nameof功能。查看公告:https : //devblogs.microsoft.com/dotnet/annoucing-f-4-7/#nameof
自 F# 4.7 起,此功能也存在于预览版中:https : //devblogs.microsoft.com/dotnet/annoucing-f-4-7/#nameof