【发布时间】:2020-10-25 07:43:52
【问题描述】:
作为问题的后续:type extension on a list in F#
我想知道是否可以使用属性扩展列表
考虑代码:
let a = []
if a.IsEmpty then ...
但我也有共同点:
if not a.IsEmpty then
这不是超级可读的,所以我想我会做一个扩展(基于托马斯在上面问题中的回答):
[<Extension>]
type ListExtensions() =
[<Extension>]
static member IsNotEmpty(l: 'T list) = not l.IsEmpty
它允许我这样做:
if a.IsNotEmpty() then
但是我有:
if a.IsEmpty then // property
if a.IsNotEmpty() then // member
有没有办法进行属性扩展,使 IsNotEmpty 也是一个属性?
【问题讨论】:
-
我认为没有!
-
我也不认为有办法做到这一点。但是
not a.IsEmpty只比a.IsNotEmpty长一个字符,而且它以not开头的事实很明显它被否定了(阅读使用a.IsNotEmpty的代码时可能很容易错过) -
我认为这有助于提高可读性,但与此同时,这主要是出于好奇:)
-
我发现总是将 bool 命名为 bool 并返回肯定的东西,然后在需要时用
not否定,这样会更容易混淆。 -
我知道它不能回答你的问题,但对于这个特定的例子来说,它是惯用的
match list with | [] -> ... | _ -> ...
标签: types f# extension-methods