在F#中的列表上键入扩展名 [英] type extension on a list in F#
问题描述
假设我有一个类型:
let MyType =
some info
...
但是,它通常用于列表中:MyType列表
but, it is commonly used in a list: MyType list
所以我可以定义:
let MyTypeList =
MyType list
是否可以在MyTypeList上定义类型扩充?
is there a way to define a type augmentation on MyTypeList?
我的实际情况是该类型返回某些工作的结果,它是分批处理的,并且我有一些代码告诉我整个批处理是否正常,部分是否正常或是否出错.如果我可以将扩展名添加到列表类型,则语法会更简单.
my practical case is that the type returns results of some work, it is handled in batches and I have some code that tell me if the whole batch is ok, if it is partially ok, or if everything went wrong. If I could add extensions to the list type, the syntax would be simpler.
let a : MyTypeList = ...
if a.IsAllOk() then ...
但是我找不到如何用列表来做到这一点.
but I can't find how to make this with a list.
推荐答案
有在F#中定义类型扩展的两种不同方式.一种选择是通过F#类型扩展,另一种是(与C#兼容)扩展方法.
There are two different ways of definining type extensions in F#. One option is via an F# type augmentation and the other is (C#-compatible) extension method.
扩展方法使您可以为特定类型的实例定义扩展,包括例如 list< MyType>
:
The extension method approach lets you define extensions for a specific type instantiation, including for example list<MyType>
:
type MyType = { N : int }
type MyTypeList = int list
[<System.Runtime.CompilerServices.Extension()>]
type MyTypeListExtensions() =
[<System.Runtime.CompilerServices.Extension()>]
static member AllOk(l:MyTypeList) = false
let foo (a:MyTypeList) =
a.AllOk()
这篇关于在F#中的列表上键入扩展名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!