扩展方法:'an object reference is required to access non-static member' 在 Travis CI 中 运行 时抛出的错误

Extension Method: 'an object reference is required to access non-static member' Error Thrown When Running in Travis CI

我正在开发一个 .net Core 项目,并试图让它与 Travis CI 一起工作。在这一点上,我遇到了一个神秘的错误,根据我对消息的解释和代码的使用方式,我无法理解这个错误。谁能帮我提供一些关于实际问题的指导?

我正在 Windows 10 机器上使用 VS 2019 进行开发,该项目在我的本地机器上构建良好,没有错误或警告。在 Travis 上,它建立在 Ubuntu Linux.

之上

Travis 中的错误消息 CI(在包含其他上下文信息的屏幕截图中也突出显示):

NumberTypeExtensions/NumberTypeExtensionLibrary.cs(348,31): error CS0176: Member 'double.IsNegative(double)' cannot be accessed with an instance reference; qualify it with a type name instead [/home/travis/build/MarkPThomas/MPT.Math-.netCore/MPT.Math/MPT.Math.csproj]

发生错误的扩展方法(通过调用power.IsNegative(0)):

    public static double Pow(this double value, double power)
    {
        if (value == 0 && power.IsNegative(0))
        {
            throw new DivideByZeroException($"{value}^{power} results in a division by zero, which is undefined.");
        }
        return NMath.Pow(value, power);
    }

调用的扩展方法:

    public static bool IsNegative(this double value, double tolerance = Numbers.ZeroTolerance)
    {
        if (value.IsZero(tolerance)) { return false; }
        return (value < NMath.Abs(tolerance));
    }

NMath & Numbers 是在其他静态 类.

上调用的静态方法

如果我更改对 power.IsNegative() 的调用,则主项目可以正常编译,但随后错误只会被推送到单元测试,调用 number.IsNegative(tolerance) 时会在此处抛出相同的错误:

    [TestCase(-0.001, 0.1, ExpectedResult = false)]
    [TestCase(0, 0.1, ExpectedResult = false)]
    [TestCase(0.001, 0.1, ExpectedResult = false)]
    [TestCase(-0.001, 0.0001, ExpectedResult = true)]
    [TestCase(-0.001, -0.0001, ExpectedResult = true)]
    public bool IsNegative_Double_Custom_Tolerance(double number, double tolerance)
    {
        return number.IsNegative(tolerance);
    }

我不确定这是否相关,但至少根据编译代码中的行号,有一个镜像函数 IsPositive 是较早定义和较早测试的,不会引发任何错误(然而?)。它在形式和用法上基本相同。

扩展方法只是语法糖,允许用户直接从对象调用其他类中定义的方法。它被称为实例方法,但实际上它是作为静态方法实现的。我不确定,但我认为您收到此错误是因为 Double.IsNegatie(double) 确实存在 (see here),因此与您的扩展方法具有相同签名的方法已经存在并且运行时认为您实际上是在尝试调用 .Net 框架静态方法而不是您的扩展方法(请注意,您在调用时没有传递可选参数,因此签名完全相同)并抛出错误,因为无法从实例调用静态方法。我认为只需重命名该方法即可。对不起,如果我的理论是错误的