好吧,我意识到这可能是一个奇怪的问题。但无论如何我还是需要问一下。其过程如下:
假设我有如下内容:
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>
我想要做的是从具有成员 MyBarFun 的 FooSeq 中过滤掉所有 Foo。可以做这样的事情吗?
我意识到我可能必须使用 :?
运算符来检查每个元素是否是 Bar
,但正如我所说 - 我必须问。我不想这样做的原因是,与 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")))
关于f# - 按约束条件过滤,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24774174/