f# - 按约束条件过滤

标签 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>

我想要做的是从具有成员 MyBarFun 的 FooSeq 中过滤掉所有 Foo。可以做这样的事情吗?

我意识到我可能必须使用 :? 运算符来检查每个元素是否是 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")))

关于f# - 按约束条件过滤,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24774174/

相关文章:

Swift - 如何声明一个接收范围内数字的方法

C# 泛型方法,new() 构造函数约束中的类型参数

f# - Lint : `x <> null` ; suggestion consider using pattern matching

f# - 类型推断 : functions vs types

f# - 如何在 FsCheck 中生成概率

java - 如何定义方法参数的类型约束?

c# - 非严格的多接口(interface)类型参数约束?

c++11 - 如何使用 C++11 static_assert 进行类型约束?

f# - 如何获得一份 list ?

.net - 通过反射创建F#记录