【问题标题】:How to define an extention method for a non-generic array?如何为非泛型数组定义扩展方法?
【发布时间】:2019-04-22 05:35:47
【问题描述】:

我无法弄清楚在非泛型数组上定义扩展方法的正确语法是什么。 This question 处理泛型数组,但为字节数组尝试类似的构造是行不通的。

我尝试了很多选择:

type Byte ``[]`` with 
type byte ``[]`` with
type Byte array with
type byte array with
type array<Byte> with
type array<byte> with
type []<Byte> with
type []<byte> with

以及所有这些用双反引号或括号包裹的结构,但没有任何作用。我下载了语言规范,但它只有一个通用数组示例。

【问题讨论】:

  • 你试过byte[]吗?
  • @FyodorSoikin 是的,没有运气。

标签: arrays f# extension-methods


【解决方案1】:

这可能是可选类型扩展的一个怪癖,can get pretty funky when generics are involved。我会改用这样的扩展方法:

open System.Runtime.CompilerServices

[<Extension>]
type ByteArrayExtensions =
    [<Extension>]
    static member inline Sum(xs: byte[]) = Array.sum xs

let f() =
    let xs = [| byte(1); byte(2); byte(3) |]
    xs.Sum()

【讨论】:

    猜你喜欢
    • 2011-04-14
    • 2023-03-10
    • 1970-01-01
    • 2011-08-28
    • 1970-01-01
    相关资源
    最近更新 更多