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

C#中如何实现int类型元组的加法运算?

C#中如何实现int类型元组的加法运算?

嘿,我来给你几个实用的解决办法,不用再手动一个个属性相加啦!


方案1:给值元组重载加法运算符

C#支持为值元组类型重载运算符,只需要写一个静态类来定义+运算符的逻辑就行。这样你就能像最初期望的那样,直接用Tuple1 + Tuple2来得到结果:

public static class TupleOperators
{
    // 针对(x:int, y:int)这种命名元组的加法重载
    public static (int x, int y) operator +((int x, int y) a, (int x, int y) b)
    {
        return (a.x + b.x, a.y + b.y);
    }
}

之后你的代码就能这么写:

var Tuple1 = (x:2,y:4);
var Tuple2 = (x:0,y:-1);
var Tuple3 = Tuple1 + Tuple2; // 结果就是(x:2,y:3),完美符合你的需求!

方案2:用扩展方法实现加法

如果觉得重载运算符有点“重”,也可以写个扩展方法,语义同样清晰:

public static class TupleExtensions
{
    public static (int x, int y) Add(this (int x, int y) tuple1, (int x, int y) tuple2)
    {
        return (tuple1.x + tuple2.x, tuple1.y + tuple2.y);
    }
}

使用的时候就调用Add方法:

var Tuple3 = Tuple1.Add(Tuple2);

方案3:自定义结构体替代元组

如果你觉得值元组的语义不够明确(比如这个元组其实代表一个坐标点),完全可以自定义一个结构体,这样代码可读性更好,还能扩展更多功能:

public struct Point
{
    public int X { get; }
    public int Y { get; }

    public Point(int x, int y) => (X, Y) = (x, y);

    // 重载加法运算符
    public static Point operator +(Point a, Point b)
    {
        return new Point(a.X + b.X, a.Y + b.Y);
    }

    // 可选:重写ToString,方便查看结果
    public override string ToString() => $"x:{X}, y:{Y}";
}

使用示例:

var point1 = new Point(2, 4);
var point2 = new Point(0, -1);
var point3 = point1 + point2; // 结果是x:2, y:3

这样不仅实现了加法,以后如果需要减法、乘法或者其他操作,都可以很方便地扩展这个结构体~

备注:内容来源于stack exchange,提问作者akTed

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.14 10:19:50