我在C#中有一个函数,它在F#中调用,在a中传递它的参数Microsoft.FSharp.Collections.List<object>
.
我怎样才能从C#函数中的F#List中获取项目?
编辑
我找到了一种循环遍历它们的"功能"样式方法,并且可以将它们传递给下面的函数以返回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;
}
Run Code Online (Sandbox Code Playgroud)
再次编辑
如下所述,F#List是Enumerable,所以上面的函数可以用行代替;
new List<LiteralType>(parameters);
Run Code Online (Sandbox Code Playgroud)
但是,有没有办法按索引引用F#列表中的项目?
Bri*_*ian 11
通常,避免将F#特定类型(如F#'list'类型)暴露给其他语言,因为体验并不是那么好(正如您所看到的).
F#列表是一个IEnumerable,所以你可以很容易地从它创建一个System.Collections.Generic.List.
没有有效的索引,因为它是单链接列表,因此访问任意元素是O(n).如果您确实需要索引,则最好更改为其他数据结构.
在我的C#-project中,我使用扩展方法轻松地在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);
}
}
Run Code Online (Sandbox Code Playgroud)
然后使用就像:
var lst = new List<int> { 1, 2, 3 }.ToFSharplist();
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
3459 次 |
最近记录: |