You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C#自定义CurrencyAmount结构体运算符重载后测试编译报错求解

问题根源

你当前的报错是运算符重载的返回值类型和测试用例的预期类型不匹配导致的:

  • 你定义的+、-运算符返回值是decimal类型,而第一个测试用例中expected是CurrencyAmount类型,两个入参类型完全不一致,编译器找不到匹配的Assert.Equal重载,才会抛出类型转换错误。
  • 第二个测试用例的两个比较值都是decimal类型,刚好匹配Assert.Equal<decimal>的重载,所以可以正常编译运行。
修复方案

推荐按结构体的封装逻辑修改运算符实现,不要直接返回decimal(会丢失币种信息,违背你把金额和币种绑定的设计初衷),将计算结果封装为CurrencyAmount实例返回:

// 修改加法运算符
public static CurrencyAmount operator +(CurrencyAmount amount1, CurrencyAmount amount2)
{
    if (amount1.currency != amount2.currency) 
        throw new ArgumentException("参与运算的币种不匹配");
    return new CurrencyAmount(amount1.amount + amount2.amount, amount1.currency);
}

// 同步修改减法运算符
public static CurrencyAmount operator -(CurrencyAmount amount1, CurrencyAmount amount2)
{
    if (amount1.currency != amount2.currency) 
        throw new ArgumentException("参与运算的币种不匹配");
    return new CurrencyAmount(amount1.amount - amount2.amount, amount1.currency);
}

如果需要Assert.Equal比较结果完全符合预期,还需要给CurrencyAmount重写Equals方法和GetHashCode方法,或者实现IEquatable<CurrencyAmount>接口:

public struct CurrencyAmount : IEquatable<CurrencyAmount>
{
    // 原有代码不变

    public bool Equals(CurrencyAmount other)
    {
        return amount == other.amount && currency == other.currency;
    }

    public override bool Equals(object obj)
    {
        return obj is CurrencyAmount other && Equals(other);
    }

    public override int GetHashCode()
    {
        return HashCode.Combine(amount, currency);
    }

    // 还可以同步重载==、!=运算符,符合比较逻辑一致性
    public static bool operator ==(CurrencyAmount left, CurrencyAmount right)
    {
        return left.Equals(right);
    }

    public static bool operator !=(CurrencyAmount left, CurrencyAmount right)
    {
        return !left.Equals(right);
    }
}

如果你不想修改运算符实现,也可以临时修改第一个测试用例的比较逻辑,只比较金额数值:

Assert.Equal(expected.amount, amount1 + amount2);

内容的提问来源于stack exchange,提问作者RonCitrus

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 10:54:05