扩展F#中的枚举类型

编程入门 行业动态 更新时间:2024-10-25 20:25:42
本文介绍了扩展F#中的枚举类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

与F#功能相关的另一个问题称为类型扩展" .

Another question related to F# feature called "Type extensions".

似乎无法在F#中扩展枚举.我经常使用 C#扩展方法来扩展枚举:添加范围验证逻辑,返回字符串表示形式等.

It seems impossible to extend enumerations in F#. I use C# Extensions Methods a lot for extending enums: add range validation logic, method that returns string representation etc.

不幸的是,似乎可能仅扩展有区别的联合,但不可能扩展简单的枚举:

Unfortunately it seems possible extend only discriminated union but impossible to extend simple enumerations:

1.内部扩展

// CustomEnum.fs module CustomEnumModule type CustomEnum = | Value1 = 1 | Value2 = 2 // Trying to split definition of the enum type CustomEnum with | Value3 = 3

错误:错误FS0010:意外符号'|'在成员定义中"

2.可选扩展名

// CustomEnumEx.fs open CustomEnumModule type CustomEnum with member public x.PrintValue() = printfn "%A" x

错误:错误FS0896:枚举不能具有成员"

对我来说,这很奇怪,因为(1)我们可以将简单枚举视为功能齐全的有区别联盟的特殊情况,并且我们可以扩展有区别的联盟,以及(2)扩展.NET枚举是在现有基础架构中添加一些功能(包括FP功能)的好方法.

It seems weird for me because (1) we can treat simple enumerations as a special case of full-featured discriminated union and we can extend discriminated unions and (2) extending .NET enums is a good way to add some features (including FP-features) to existing infrastructure.

此行为是故意的还是实施中的简单错误?

Is this behavior intentional or this is simple bug in implementation?

P.S.不幸的是, F#Spec 在这方面保持沉默,至少我在那里找不到任何一种或另一种行为的证据.

P.S. Unfortunately F# Spec is silent in this regard, or at least I can't find any proofs for one or another behavior there.

推荐答案

可以创建与该类型同名的模块,类似于扩展该类型:

It is possible to create a module with the same name as a type which is similar to extending the type:

type CustomEnum = Value1 = 1 | Value2 = 2 [<CompilationRepresentation(CompilationRepresentationFlags.ModuleSuffix)>] module CustomEnum = let Print = function | CustomEnum.Value1 -> "One" | CustomEnum.Value2 -> "Two" | _ -> invalidArg "" "" let value = CustomEnum.Value1 let s = CustomEnum.Print value

更多推荐

扩展F#中的枚举类型

本文发布于:2023-07-30 15:20:25,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1250592.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:类型

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!