F# - 公共文字

时间:2009-12-02 18:37:06

标签: f#

有没有办法在类型上定义公共文字(C#中的公共const)?显然,类型中的绑定必须是私有的,并且Literal属性不能应用于成员。

1 个答案:

答案 0 :(得分:9)

使用[< Literal>]属性。这就是你正在寻找的魔力。此外,将文字属性放在诸如字符串之类的值上使其能够在模式匹配中使用。例如:

// 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#中公开一个公共const / public readonly字段,我会调查它。