F# return ICollection

梦想的初衷 提交于 2020-01-21 08:49:52

问题


I'm working with a library created in C#. I've been working on porting some code to F# but must use quite a few underlying types from the C# lib.

One piece of code needs to calculate a list of values and assign it to a public field/property in the class. The field is a C# class that contains two ICollection.

My F# code works fine and needs to return an F# Seq/List.

I tried the following code snippets which each produce errors.

  • Return type of F# member is a type called recoveryList with type Recoveries list
  • Public field in class that is a class itself containing two ICollection objects

    this.field.Collection1 = recoveries
    

This gives the error Expected to have type ICollection but has type Recoveries list

this.field.Collection1 = new ResizeArray<Recoveries>()

Gives the error expected type ICollection but is ResizeArray

this.field.Collection1 = new System.Collections.Generic.List<Recoveries>()

Same error as above - expected ICollection but type is List

Any ideas? These operations seem valid from a C# point of view and List/ResizeArray implements ICollection so... I am confused how to assign the value.

I could change the type of the underlying C# library, but this might have other implications.

Thanks


回答1:


F# doesn't do implicit casting like C#. So even though System.Collections.Generic.List<'T> implements the ICollection interface, you can't directly set some ICollection-typed property to an instance of System.Collections.Generic.List<'T>.

The fix is easy though -- all you need to do is add an explicit upcast to ICollection to your ResizeArray<'T> or System.Collections.Generic.List<'T> before assigning it:

// Make sure to add an 'open' declaration for System.Collections.Generic
this.field.Collection1 = (recoveries :> ICollection)

or

this.field.Collection1 = (ResizeArray<Recoveries>() :> ICollection)


来源:https://stackoverflow.com/questions/14912548/f-return-icollection

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!