F# - public literal

旧巷老猫 提交于 2019-12-19 05:58:10

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/1834923/f-public-literal

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