F#返回ICollection

编程入门 行业动态 更新时间:2024-10-27 10:26:26
本文介绍了F#返回ICollection的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在使用C#创建的库.我一直在努力将一些代码移植到F#,但必须使用C#库中的许多基础类型.

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.

一段代码需要计算一个值列表,并将其分配给该类中的公共字段/属性.该字段是一个包含两个ICollection的C#类.

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.

我的F#代码工作正常,需要返回一个F#Seq/List.

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

我尝试了以下每个都会产生错误的代码段.

I tried the following code snippets which each produce errors.

  • F#成员的返回类型是具有恢复列表类型的称为recoveryList的类型
  • 类中的公共字段,它是一个类本身包含两个ICollection对象

  • 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

这给出了错误,预期为ICollection类型,但类型为恢复列表"

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

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

给出错误的预期类型ICollection但为ResizeArray

Gives the error expected type ICollection but is ResizeArray

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

与上述相同的错误-预期为ICollection,但类型为List

Same error as above - expected ICollection but type is List

有什么想法吗?从C#的角度来看,这些操作似乎是有效的,并且List/ResizeArray实现了ICollection,所以...我很困惑如何分配值.

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.

我可以更改基础C#库的类型,但这可能会带来其他影响.

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

谢谢

推荐答案

F#不会像C#那样进行隐式转换.因此,即使System.Collections.Generic.List<'T>实现了ICollection接口,您也不能直接 将某些ICollection类型的属性设置为System.Collections.Generic.List<'T>的实例.

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>.

修复很容易-您所需要做的就是在分配ResizeArray<'T>或System.Collections.Generic.List<'T>之前将ICollection的显式上行链路添加到

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)

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

更多推荐

F#返回ICollection

本文发布于:2023-11-12 09:30:40,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1581116.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:ICollection

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!