F#实现C#接口时的编译错误

时间:2014-02-21 20:43:38

标签: interface f#

我有这个用C#编写的界面......

public interface IFoo {
    IEnumerable<T> Bar<T>(IEnumerable<T> list); 
}

简单的C#实现很简单......

public class CsFoo : IFoo
{
    public IEnumerable<T> Bar<T>(IEnumerable<T> list)
    {
        return list;
    }
}

简单的F#实现也很简单......

type FsFoo() =
    interface IFoo with
        member this.Bar list =
            list

但是当我尝试在列表中匹配 ...

type FsFoo() =
    interface IFoo with
        member this.Bar list =
            match list with
                | [] -> []        // error                      
                | list -> list

我收到此错误...

  

预计此表达式具有类型   System.Collections.Generic.IEnumerable&LT;'一&GT;但这里有'b list

类型

你能帮我理解这个错误,以及我应该如何更改F#代码来修复它?

谢谢...

1 个答案:

答案 0 :(得分:3)

您的界面不使用列表,它使用IEnumerable<T>,因此在处理F#中的界面时应使用Seq

type FsFoo() =
    interface IFoo with
        member this.Bar list =
            match Seq.isEmpty list with
                | true -> Seq.empty        // input is empty               
                | false -> list            // input is not empty

但它实际上毫无意义,因为它只是将参数值作为结果值传递,所以它与

完全相同
type FsFoo() =
    interface IFoo with
        member this.Bar list = list