簡體   English   中英

F# - 公共文字

[英]F# - public literal

有沒有辦法在類型上定義公共文字(C#中的公共const)? 顯然,類型中的綁定必須是私有的,並且Literal屬性不能應用於成員。

使用[<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字段,我會調查一下。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM