与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#中的枚举类型
发布评论