F# 按约束过滤

F# 按约束过滤,f#,type-constraints,F#,Type Constraints,好吧,我意识到这可能是个奇怪的问题。但我还是要问一下。内容如下: 假设我有如下内容: type Foo() = member this.MyFooFun i = 2*i type Bar() = inherit Foo() member this.MyBarFun i = 3*i type Baz() = inherit Foo() member this.MyBazFun i = 5*i type FooSeq = seq<Foo>

好吧,我意识到这可能是个奇怪的问题。但我还是要问一下。内容如下:

假设我有如下内容:

type Foo() =
    member this.MyFooFun i = 2*i

type Bar() =
    inherit Foo()
    member this.MyBarFun i = 3*i

type Baz() =
    inherit Foo()
    member this.MyBazFun i = 5*i

type FooSeq = seq<Foo>
type Foo()=
成员this.MyFooFun i=2*i
类型栏()=
继承Foo()
成员this.MyBarFun i=3*i
Baz()型=
继承Foo()
成员this.MyBazFun i=5*i
类型FooSeq=seq
我想做的是,从包含成员MyBarFun的FooSeq中筛选出所有的Foo。有可能做那样的事吗


我意识到我可能必须使用
:?
操作符来检查每个元素是否是
,但正如我所说的,我必须询问。我不想这样做的原因是,与
Foo
Bar
Baz
相对应的类型位于公司其他地方开发的库中。在任何给定的时间,可能会添加更多包含
MyBarFun
-成员的类型。

如果您只想在子类型上进行筛选,则很容易:

let foos = candidates |> Seq.filter (fun x -> not (x :? Bar))
如果您明确希望过滤掉具有名为“MyBarFun”的成员的类型,则需要使用反射:

let foos' =
    candidates
    |> Seq.filter (fun x ->
        not (x.GetType().GetMembers() |> Array.exists (fun m ->
            m.Name = "MyBarFun")))

如果所有的子类型都具有一个中间类型,或者实现一个接口,比如<代码> IyBaFaluy ,这将使你的生活更容易。有关:请考虑告诉我们一些你正在试图解决的实际问题的细节。虽然人们可能会为你的问题找到直接的答案,但很有可能通过了解“大局”,整个问题会得到很好且简单的解决方案。我想筛选具有名为
MyBarFun
的成员的类型(这样他们就只剩下了)。然后我想用
Seq.map
调用它们。正如我所预料的,我将不得不使用反射来实现这一点,因为
MyBarFun
并没有被抽象成一个接口。谢谢。:)