按约束筛选



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

假设我有如下内容:

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>

我想做的是过滤掉所有的Foo's从FooSeq有成员MyBarFun。有可能那样做吗?

我意识到我可能不得不使用:?运算符来检查每个元素是否为Bar,但正如我所说-我必须问。我不愿意这样做的原因是,FooBarBaz对应的类型在公司其他地方开发的库中。在任何给定的时间,可能会添加更多包含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")))