ran*_*eur 4 f# record discriminated-union
我知道可以为有区别的联合添加方法和属性,但是你可以添加一个必须在创建联合的实例时设置的不可变字段,就像记录中的字段一样吗?
我想我想要做的是组合一个union类型和一个记录类型,如下所示:
type union =
| OptionOne of int
| OptionTwo of string
{
AFieldUsedForBothCases : string
}
Run Code Online (Sandbox Code Playgroud)
这不是有效的声明.
我知道这可以通过创建记录类型来解决:
type record =
{
AFieldUsedForBothCases : string
TheDiscriminatedUnion : union
}
Run Code Online (Sandbox Code Playgroud)
但是如果可能的话,我想做第一个例子.
不,我不这么认为,但你可以将它附加到两个案例并用成员提取它:
type union =
| OptionOne of int * string
| OptionTwo of string * string
member u.AFieldUsedForBothCases =
match u with
| OptionOne (_,s) | OptionTwo(_,s) -> s
Run Code Online (Sandbox Code Playgroud)
最后,您必须在构造函数中指定其他元素.好吧,这个会让你重新键入每个构造函数的公共元素,但我认为它并没有那么糟糕.