单一案例歧视联合

单一案件歧视联合就像任何其他受歧视的联合一样,只是它只有一个案例。

// Define single-case discriminated union type.
type OrderId = OrderId of int
// Construct OrderId type.
let order = OrderId 123
// Deconstruct using pattern matching. 
// Parentheses used so compiler doesn't think it is a function definition.   
let (OrderId id) = order

它对于强制类型安全很有用,并且常用于 F#而不是 C#和 Java,其中创建新类型会带来更多开销。

以下两种替代类型定义导致声明相同的单一案例区分联合:

type OrderId = | OrderId of int

type OrderId =
      | OrderId of int