F# return ICollection

2020-03-26 05:10发布

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条回答
小情绪 Triste *
2楼-- · 2020-03-26 05:29

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)
查看更多
登录 后发表回答