F# - (NUnit ApplyTo) 成员匹配多个重载...请将其限制为一个

F# - (NUnit ApplyTo) member matches multiple overloads ... please restrict it to one

我正在尝试编写自定义相等约束来比较 2 个对象。

open FsUnit
open NUnit.Framework.Constraints

type equalCompany(expected:Company) = 
    inherit Constraints.EqualConstraint(expected)    

    override this.ApplyTo (actual:Company option) = 
        //actual.IsSome |> should equal True
        //actual.Value.Id |> should equal expected.Id

        ConstraintResult(this, actual, true)

// example of usage:
actualCompany |> should equalCompany expectedCompany

它抱怨是因为 ApplyTo 实现 匹配多个重载 而我找不到正确的语法。
理想情况下,我喜欢与 Company 选项 进行比较,但仍然只是 Company 就可以了。

涉及的类型如下:

type CompanyType =
    | Bank
    | Exchange

type Company = {
    Id: string
    Types: CompanyType list
}

并且我正在尝试编写我的相等约束,因为简单的现有 equal 不能与类型一起正常工作(列表,即使排序,也总是不同的)

如何正确覆盖 ApplyTo 函数?

我认为问题是您试图覆盖的 ApplyTo 方法是通用的,需要有一个签名 ApplyTo<'T> : 'T -> ConstraintResult

如果我对您的代码的理解正确,您是在尝试定义 CompanyCompany option 之间的比较。为此,您需要检查(在运行时)传递给 ApplyTo 的值的类型是否正确。然后你可以转换它并实现你需要的任何逻辑。

这是一个对我有用的最小示例,以 F# 脚本文件的形式编写:

#r "nuget: nunit"
#r "nuget: fsunit"

type Company(s) = 
  member x.Name = s

open FsUnit
open NUnit.Framework.Constraints

type equalCompany(expected:Company) = 
    inherit EqualConstraint(expected)    

    override this.ApplyTo<'T>(actual:'T) = 
        match box actual with 
        | :? option<Company> as co ->
          ConstraintResult(this, actual, 
            co.IsSome && co.Value.Name = expected.Name)
        | _ ->
          ConstraintResult(this, actual, false)

let actualCompany = Company("Test")
let expectedCompany = Company("Test")

// This passes, because it has the right type
Some actualCompany |> should equalCompany expectedCompany

// This does not, because the 'ApplyTo' logic does not handle this type
actualCompany |> should equalCompany expectedCompany