扩展现有类的索引器 [英] Extending the Indexer for an existing class

查看:50
本文介绍了扩展现有类的索引器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我的A类型实现了索引器,例如类型A是一个库.现在我想扩展它的索引器,例如在这里我想将浮点数添加到索引器中.

Suppose I have type A with indexer implemented, e.g. type A is a library. Now I want to extend the indexer of it, e.g. here I want to add float number into the indexer.

我计算出以下代码:

type A(a:int array) = 
  member this.Item
    with get(x) = a.[x]
    and  set(x) value = a.[x] <- value

type A with
    member m.Item with
     get(x:float) = m.[x |> int]
     and  set(x:float) v = m.[x |> int] <- v

但它似乎不起作用:

let a = A([| 1;2;3 |])
a.[1]
a.[1] <- 10

a.[1.0]

对于最后一行,我得到:

For the last line, I get:

Script1.fsx(243,4): error FS0001: This expression was expected to have type
    int    
but here has type
    float    

在F#中可以扩展索引器吗?谢谢!

Is extending indexer possible in F#? Thanks!

推荐答案

当类型扩展名是在单独的程序集(或单独的模块)中定义的,并且与类型定义在同一模块中时,这种行为会有所不同.

This behaves differently when the type extension is defined in a separate assembly (or separate module) and when it is in the same module as the type definition.

>

  • 当两者都在同一个模块中时,F#将它们编译为一个类,并且 Item 成为标准的重载索引器-在这种情况下,您的代码可以按预期工作(这就是您实际上是在这里写的.)

    • When both are in the same module, F# compiles them into a single class and Item becomes a standard overloaded indexer - In this case, your code works as expected (and this is how you actually wrote it here).

    当它们在单独的模块中时,F#将索引器编译为扩展成员.在这种情况下,我会收到您描述的错误消息.

    When they are in separate modules, F# compiles the indexer as an extension member. In this case, I get the error message you described.

    可以使用扩展成员(例如new方法)添加新的重载.据我所知,规格并未说这不适用于索引器,因此我认为这是一个错误(您可以将其报告给 microsoft com ?)

    Adding new overloads using extension members (e.g. new method) is possible. As far I can see, the specificaton doesn't say that this shouldn't work for indexers, so I think it is a bug (can you report it to fsbugs at microsoft dot com?)

    这篇关于扩展现有类的索引器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆