受歧视联盟中的不可变字段

发布于 2024-12-04 06:51:44 字数 453 浏览 1 评论 0原文

我知道可以向可区分的联合添加方法和属性,但是您是否可以添加一个在创建联合实例时必须设置的不可变字段,就像记录中的字段一样?

我想我想做的是将联合类型和记录类型结合起来,如下所示:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

杀お生予夺 2024-12-11 06:51:44

不,我不这么认为,但您可以将其附加到这两种情况并使用成员提取它:

type union =
    | OptionOne of int * string
    | OptionTwo of string * string
    member u.AFieldUsedForBothCases =
        match u with
        | OptionOne (_,s) | OptionTwo(_,s) -> s

最后您必须在构造函数中指定附加元素。好的,这个可以让您在每个构造函数上重新输入公共元素,但我认为这还不错。

No I don't think so, but you can append it to both cases and extract it with a member:

type union =
    | OptionOne of int * string
    | OptionTwo of string * string
    member u.AFieldUsedForBothCases =
        match u with
        | OptionOne (_,s) | OptionTwo(_,s) -> s

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.

明月松间行 2024-12-11 06:51:44

我认为这是一个更简洁的解决方案

type union=
|a of int
|b of string

type Realtype = string * union

感谢类型检查,您可以强制属性设置,并且我认为它比记录解决方案更简洁

I think this is a neater solution

type union=
|a of int
|b of string

type Realtype = string * union

Thanks to type checking, you can force the property setting, and I think it is a little neater than the record solution

牵你手 2024-12-11 06:51:44

我认为这是不可能的。除此之外,我认为你的第二个代码(使用记录)更有意义,因为 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文