Accessing an F# list from inside C# code

前端 未结 2 1114
囚心锁ツ
囚心锁ツ 2021-01-12 22:20

I have written an F# module that has a list inside:

module MyModule
type X = 
    {
        valuex : float32
    }
let         


        
相关标签:
2条回答
  • 2021-01-12 23:00

    As simple as:

    IList<MyModule.X> list = MyModule.l.ToList();
    

    The reason you need the conversion method rather than a cast / implicit conversion is because an FSharpList<T> implements IEnumerable<T> but not IList<T> since it represents an immutable linked-list.

    Note that you'll have to include FSharp.Core as a reference in your C# project.

    0 讨论(0)
  • 2021-01-12 23:05

    The FSharpList<T> (which is the .Net name of the F# list<T> type) doesn't implement IList<T>, because it doesn't make sense.

    IList<T> is for accessing and modifying collections that can be accessed by index, which list<T> is not. To use it from C#, you can either use the type explicitly:

    FSharpList<MyModule.X> l = MyModule.l;
    var l = MyModule.l; // the same as above
    

    Or you can use the fact that it implements IEnumerable<T>:

    IEnumerable<MyModule.X> l = MyModule.l;
    

    Or, if you do need IList<T>, you can use LINQ's ToList(), as Ani suggested:

    IList<MyModule.X> l = MyModule.l.ToList();
    

    But you have to remember that F# list is immutable and so there is no way to modify it.

    0 讨论(0)
提交回复
热议问题