【问题标题】:F#: Using a F# indexed property from C#F#:使用 C# 中的 F# 索引属性
【发布时间】:2015-04-01 14:00:29
【问题描述】:

我用 F# 编写了一个实现接口的类,以便为我的 F# 程序集构建一个 C# 友好的接口。

我已经将一些属性编写为索引属性。但是,当我尝试使用 C# 中的类型时,我只能在智能感知中获得合成的 get_PropertyName 方法,并且编译器同样会抱怨,以防我想像使用 C# 那样使用索引属性。

参考代码:

type IMyInterfaceType =   
    abstract MyProperty : MyType1 with get
    abstract MyIndexedProperty : MyType2 -> MyType3 with get
    abstract MyTwoDimensionalIndexedProperty : (MyType4 * MyType5) -> MyType6 with get

type MyInterfaceType =   

    new () = { }

    interface IMyInterfaceType with
        member this.MyProperty with get () = new MyType1 ()
        member this.MyIndexedProperty with get parameter = new MyType3 ()
        member this.MyTwoDimensionalIndexedProperty with get pair = new MyType6 ()

尝试从 C# 访问此类时,我只获取方法

get_MyIndexedProperty(MyType2 parameter)
get_MyTwoDimensionalIndexedProperty(Tuple<MyType4, MyType5>)

而不是我希望的索引属性。

我做错了什么还是这是一个已知问题?

干杯
--马蒂亚斯。

【问题讨论】:

    标签: f#


    【解决方案1】:

    回复原问题:

    C# 中的索引器属性具有特殊名称 Item,因此要创建可从 C# 访问的索引器,您必须将索引器属性命名为“Item”,例如:

    type X () =
        member this.Item with get key = ....
    

    现在可以在 F# 中使用 (x : X).[key] 或在 C# 中使用 x[key] 访问它。

    对更新问题的回应:

    C# 不像 F# 那样支持索引属性。建议使用其他类型:https://msdn.microsoft.com/en-us/library/aa288464%28v=vs.71%29.aspx

    所以你可以尝试使用这样的东西:

    [<AbstractClass>]
    type Indexer<'index, 'result> () =
        abstract Get : 'index -> 'result
        member this.Item with get key = this.Get key
    
    type IMyInterfaceType =   
        abstract MyProperty : MyType1 with get
        // F# indexed propetties
        abstract MyIndexedProperty : MyType2 -> MyType3 with get
        // C# workaround
        abstract MyCSharpIndexedProperty : Indexer<MyType2, MyType3> with get
    
    type MyInterfaceType () as this =
        let proxy =
          { new Indexer<MyType2, MyType3> () with
              member __.Get key = (this :> IMyInterfaceType).MyIndexedProperty key }
        interface IMyInterfaceType with
            member __.MyProperty with get () = new MyType1 ()
            member __.MyIndexedProperty with get key = new MyType3 ()
            member __.MyCSharpIndexedProperty with get () = proxy
    

    和二维属性类似,通过创建Indexer&lt;'index1, 'index2, 'result&gt; () = ...

    【讨论】:

    • 啊,我明白了!像 object.Property[key] 这样的调用在 C# 中工作,因为属性的类型有一个索引器,而不是索引位于属性类中的属性的能力。感谢您的澄清!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-18
    • 1970-01-01
    • 2021-03-05
    • 2015-01-26
    • 1970-01-01
    相关资源
    最近更新 更多