F#-公共文字 [英] F# - public literal
问题描述
是否可以在类型上定义公共文字(在C#中为public const)?显然,让类型中的绑定必须是私有的,并且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.
我看到问题是关于如何将它们放在自定义类(而不是模块)中的.我不知道您是否可以在F#中公开public const/public readonly字段,我将对其进行调查.
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.
这篇关于F#-公共文字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!