【问题标题】:Why does F# using Xunit require type information when Asserting equality on Strings为什么在字符串上断言相等时使用 Xunit 的 F# 需要类型信息
【发布时间】:2012-02-27 03:05:41
【问题描述】:

我正在使用 F# 和 Xunit。 (我对两者都比较陌生)

我发现当我使用 Xunit 的 Assert.Equal() 时,当被比较的类型是字符串时,我需要指定 "<string>"

例如这个运行和编译:

[<Fact>]
let Test_XunitStringAssertion() =
    let s1 = "Stuff"
    Assert.Equal<string>("Stuff",s1)

我的问题是,为什么我不能删除 "&lt;string&gt;" 而只是断言 "Assert.Equal("Stuff",s1)" 代替?

在我看来编译器知道这两个参数的类型,所以为什么要大惊小怪?

以下是编译Assert.Equal("Stuff",s1)时返回的错误:

error FS0041: A unique overload for method 'Equal' could not be determined based on type information prior to this program point. The available overloads are shown below (or in the Error List window). A type annotation may be needed.
error FS0041: Possible overload: 'Assert.Equal<'T>(expected: 'T, actual: 'T) : unit'.
error FS0041: Possible overload: 'Assert.Equal<'T>(expected: seq<'T>, actual: seq<'T>) : unit'.
error FS0041: Possible overload: 'Assert.Equal<'T>(expected: 'T, actual: 'T, comparer: System.Collections.Generic.IEqualityComparer<'T>) : unit'.
error FS0041: Possible overload: 'Assert.Equal(expected: float, actual: float, precision: int) : unit'.
error FS0041: Possible overload: 'Assert.Equal(expected: decimal, actual: decimal, precision: int) : unit'.
error FS0041: Possible overload: 'Assert.Equal<'T>(expected: seq<'T>, actual: seq<'T>, comparer: System.Collections.Generic.IEqualityComparer<'T>) : unit'.

【问题讨论】:

标签: f# xunit


【解决方案1】:

这是因为string 可以被第一个和第二个 重载匹配(记住:string :&gt; seq&lt;char&gt;)。

【讨论】:

    【解决方案2】:

    您删除了&lt;string&gt; 的示例对我来说运行没有错误,正如我所期望的那样(尽管@Ramon Snir 指出string :&gt; seq&lt;char&gt;,但重载解析算法通过识别提供的string 类型是“比seq&lt;char&gt; 更接近”。

    [<Fact>]
    let Test_XunitStringAssertion() =
        let s1 = "Stuff"
        Assert.Equal("Stuff",s1)
    

    我猜您提供的示例与导致您出现问题的真实代码不完全相同。也许你真实代码中的s1 实际上不是string(或者至少编译器不知道它是)。

    【讨论】:

      猜你喜欢
      • 2011-08-08
      • 2018-06-28
      • 1970-01-01
      • 2010-09-29
      • 2012-12-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-07
      相关资源
      最近更新 更多