F# 扩展F中的枚举类型#
另一个与F#特性相关的问题叫做 在F#中扩展枚举似乎是不可能的。我使用了很多扩展枚举的方法:添加范围验证逻辑、返回字符串表示的方法等等 不幸的是,似乎可以只扩展有区别的并集,但不可能扩展简单枚举: 1。内在扩展F# 扩展F中的枚举类型#,f#,extension-methods,F#,Extension Methods,另一个与F#特性相关的问题叫做 在F#中扩展枚举似乎是不可能的。我使用了很多扩展枚举的方法:添加范围验证逻辑、返回字符串表示的方法等等 不幸的是,似乎可以只扩展有区别的并集,但不可能扩展简单枚举: 1。内在扩展 // CustomEnum.fs module CustomEnumModule type CustomEnum = | Value1 = 1 | Value2 = 2 // Trying to split definition of the enum type C
// CustomEnum.fs
module CustomEnumModule
type CustomEnum =
| Value1 = 1
| Value2 = 2
// Trying to split definition of the enum
type CustomEnum with
| Value3 = 3
// CustomEnumEx.fs
open CustomEnumModule
type CustomEnum with
member public x.PrintValue() =
printfn "%A" x
错误:“错误FS0010:成员定义中意外的符号“|”
2。可选扩展名
// CustomEnum.fs
module CustomEnumModule
type CustomEnum =
| Value1 = 1
| Value2 = 2
// Trying to split definition of the enum
type CustomEnum with
| Value3 = 3
// CustomEnumEx.fs
open CustomEnumModule
type CustomEnum with
member public x.PrintValue() =
printfn "%A" x
错误:“错误FS0896:枚举不能有成员”
这对我来说似乎很奇怪,因为(1)我们可以将简单枚举视为全功能歧视联合的特例,我们可以扩展歧视联合,并且(2)扩展.NET枚举是向现有基础结构添加一些功能(包括FP功能)的好方法
这种行为是故意的还是实现中的简单错误
不幸的是,p.S.在这方面没有提及,或者至少我找不到任何证据证明存在一种或另一种行为。可以创建一个与类型同名的模块,类似于扩展类型:
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
类型CustomEnum=Value1=1 | Value2=2
[]
模块自定义枚举=
让打印=函数
|CustomEnum.Value1->“一个”
|CustomEnum.Value2->“两个”
|“残疾人士”
让值=CustomEnum.Value1
设s=CustomEnum.Print值
不久前,在Hubfs(又名FPish)上也有类似的问题:这表明这是不可能的,这是出于设计原因。谢谢链接。我同意这可能是有意的。我不明白这个决定背后的理由。谢谢,这是一个很好的解决方案。我仍然在想,为什么F#dev团队决定不为Enum实现此功能。我建议通过fsbugs-at-microsoft.com向F#团队提供有关此问题的反馈,他们已经响应并修复了我报告的许多问题。Thansks,我一定会这样做!