Continued “Is there an equivalent of C#'s nameof(..) in F#?”

生来就可爱ヽ(ⅴ<●) 提交于 2020-12-10 17:01:24

问题


With reference to Is there an equivalent of C#'s nameof(..) in F#?

how can the nameof function used or extended for the following case?

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

The compiler gives the following error:

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


回答1:


The answer you linked is a bit outdated. F# 5.0 (released just recently) offers the true nameof feature. See the announcement: https://devblogs.microsoft.com/dotnet/announcing-f-4-7/#nameof

This feature also existed in preview since F# 4.7: https://devblogs.microsoft.com/dotnet/announcing-f-4-7/#nameof




回答2:


You can write your code like this:

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)

The type annotation is needed due to overloading. Not sure why there is a generic type parameter on the class declaration, but it's not used anywhere so I just removed it.



来源:https://stackoverflow.com/questions/65119270/continued-is-there-an-equivalent-of-cs-nameof-in-f

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!