简体   繁体   中英

F# - public literal

Is there a way to define a public literal (public const in C#) on a type? Apparently let bindings in types must be private and the Literal attribute can't be applied to members.

Use the [< Literal >] attribute. This does the magic you are looking for. In addition, putting the literal attribute on a value such as a string enables it to be used within pattern matching. For example:

// BAD - introduces new value named 'Name'
let Name = "Chris Smith"

match Console.ReadLine() with
| Name -> printfn "You entered my name! %s" Name
| _ -> printfn "You didn't enter my name"

// Good - uses the literal value, matches against the value Name
[<Literal>]
let NameLiteral = "Chris Smith"
match Console.ReadLine() with
| NameLiteral -> "You entered my name!"
| _ -> printfn "You didn't enter my name.

Edit: I see that the question is referring to how to put these within custom classes (and not modules). I do not know if you can expose a public const / public readonly field within F#, I'll look into it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM