[英]Retrieving items from an F# List passed to C#
I have a function in C# that is being called in F#, passing its parameters in a Microsoft.FSharp.Collections.List<object>
. I have a function in C# that is being called in F#, passing its parameters in a
Microsoft.FSharp.Collections.List<object>
.
How am I able to get the items from the F# List in the C# function?如何从 C# function 中的 F# 列表中获取项目?
EDIT编辑
I have found a 'functional' style way to loop through them, and can pass them to a function as below to return C# System.Collection.List:我找到了一种“功能”风格的方式来遍历它们,并且可以将它们传递给 function,如下所示返回 C# System.Collection.List:
private static List<object> GetParams(Microsoft.FSharp.Collections.List<object> inparams)
{
List<object> parameters = new List<object>();
while (inparams != null)
{
parameters.Add(inparams.Head);
inparams = inparams.Tail;
}
return inparams;
}
EDIT AGAIN再次编辑
The F# List, as was pointed out below, is Enumerable, so the above function can be replaced with the line; F# List,如下文所指出的,是可枚举的,所以上面的 function 可以换行;
new List<LiteralType>(parameters);
Is there any way, however, to reference an item in the F# list by index?但是,有什么方法可以按索引引用 F# 列表中的项目?
In general, avoid exposing F#-specific types (like the F# 'list' type) to other languages, because the experience is not all that great (as you can see).通常,避免将 F# 特定类型(如 F# 'list' 类型)暴露给其他语言,因为体验并不是那么好(如您所见)。
An F# list is an IEnumerable, so you can create eg a System.Collections.Generic.List from it that way pretty easily. F# 列表是一个 IEnumerable,因此您可以很容易地从中创建一个 System.Collections.Generic.List。
There is no efficient indexing, as it's a singly-linked-list and so accessing an arbitrary element is O(n).没有有效的索引,因为它是一个单链表,因此访问任意元素是 O(n)。 If you do want that indexing, changing to another data structure is best.
如果您确实需要该索引,最好更改为另一种数据结构。
In my C#-project I made extension methods to convert lists between C# and F# easily:在我的 C# 项目中,我创建了扩展方法来轻松转换 C# 和 F# 之间的列表:
using System;
using System.Collections.Generic;
using Microsoft.FSharp.Collections;
public static class FSharpInteropExtensions {
public static FSharpList<TItemType> ToFSharplist<TItemType>(this IEnumerable<TItemType> myList)
{
return Microsoft.FSharp.Collections.ListModule.of_seq<TItemType>(myList);
}
public static IEnumerable<TItemType> ToEnumerable<TItemType>(this FSharpList<TItemType> fList)
{
return Microsoft.FSharp.Collections.SeqModule.of_list<TItemType>(fList);
}
}
Then use just like:然后像这样使用:
var lst = new List<int> { 1, 2, 3 }.ToFSharplist();
Answer to edited question:回答已编辑的问题:
Is there any way, however, to reference an item in the F# list by index?
但是,有什么方法可以按索引引用 F# 列表中的项目?
I prefer f# over c# so here is the answer:我更喜欢 f# 而不是 c# 所以这里是答案:
let public GetListElementAt i = mylist.[i]
returns an element (also for your C# code).返回一个元素(也适用于您的 C# 代码)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.