受歧视联盟中的不可变字段
我知道可以向可区分的联合添加方法和属性,但是您是否可以添加一个在创建联合实例时必须设置的不可变字段,就像记录中的字段一样?
我想我想做的是将联合类型和记录类型结合起来,如下所示:
type union =
| OptionOne of int
| OptionTwo of string
{
AFieldUsedForBothCases : string
}
这不是有效的声明。
我知道这可以通过创建记录类型来解决:
type record =
{
AFieldUsedForBothCases : string
TheDiscriminatedUnion : union
}
但如果可能的话,我想做一些与第一个示例类似的事情。
I know it's possible to add methods and properties to discriminated unions, but can you add an immutable field that has to be set when an instance the union is created, much like the fields in a record?
I guess what I'd like to do is combine a union type and a record type, like this:
type union =
| OptionOne of int
| OptionTwo of string
{
AFieldUsedForBothCases : string
}
which isn't a valid declaration.
I know this can be solved by creating a record type:
type record =
{
AFieldUsedForBothCases : string
TheDiscriminatedUnion : union
}
but I'd like to do something similar to the first example if possible.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
不,我不这么认为,但您可以将其附加到这两种情况并使用成员提取它:
最后您必须在构造函数中指定附加元素。好的,这个可以让您在每个构造函数上重新输入公共元素,但我认为这还不错。
No I don't think so, but you can append it to both cases and extract it with a member:
In the end you have to specify the additional element in your constructor anyway. Ok, this one will let you retype the common element on every constructor but I think it's not that bad.
我认为这是一个更简洁的解决方案
感谢类型检查,您可以强制属性设置,并且我认为它比记录解决方案更简洁
I think this is a neater solution
Thanks to type checking, you can force the property setting, and I think it is a little neater than the record solution
我认为这是不可能的。除此之外,我认为你的第二个代码(使用记录)更有意义,因为 DU 是关于“这个或那个或那个......”,现在如果所有这些情况之间有一些共同点,那么我会保留这个共同点在 DU 之外而不是在 DU 内部。
I don't think that is possible. Apart form that I think your second code (using records) makes much more sense because DUs is about "either this or that or that ...", now if there is something common in between all those cases then I would keep that common thing out of the DU rather then inside the DU.