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

C#泛型Matrix类实现不同INumber类型矩阵相加方法问询

实现不同泛型类型Matrix的加法运算

要支持不同类型矩阵相加,你需要利用IAdditionOperators<TSelf, TOther, TResult>接口约束类型间的加法能力,同时通过泛型参数推导自动确定返回的矩阵类型。

步骤1:扩展类的基础结构与同类型加法

先完善矩阵类的基础功能,保留已实现的同类型加法:

public class Matrix<T> where T : INumber<T>
{
    private int _width, _height;
    private T[,] _vals;

    // 构造函数:初始化矩阵尺寸
    public Matrix(int width, int height)
    {
        _width = width;
        _height = height;
        _vals = new T[width, height];
    }

    // 索引器:简化矩阵元素的读写
    public T this[int x, int y]
    {
        get => _vals[x, y];
        set => _vals[x, y] = value;
    }

    // 原有同类型加法运算符
    public static Matrix<T> operator +(Matrix<T> first, Matrix<T> second)
    {
        if (first._width != second._width || first._height != second._height)
            throw new ArgumentException("矩阵尺寸不匹配");

        var result = new Matrix<T>(first._width, first._height);
        for (int x = 0; x < first._width; x++)
            for (int y = 0; y < first._height; y++)
                result[x, y] = first[x, y] + second[x, y];
        return result;
    }

步骤2:实现跨类型加法运算符

添加泛型版本的+运算符,通过接口约束确保两种类型可以相加,并自动推导结果类型:

// 跨类型加法:Matrix<T> + Matrix<U> → Matrix<TAddResult>
    public static Matrix<TAddResult> operator +<U, TAddResult>(Matrix<T> first, Matrix<U> second)
        where U : INumber<U>
        where T : IAdditionOperators<T, U, TAddResult>
        where TAddResult : INumber<TAddResult>
    {
        if (first._width != second._width || first._height != second._height)
            throw new ArgumentException("矩阵尺寸不匹配");

        var result = new Matrix<TAddResult>(first._width, first._height);
        for (int x = 0; x < first._width; x++)
            for (int y = 0; y < first._height; y++)
                result[x, y] = first[x, y] + second[x, y];
        return result;
    }
}

关键细节说明

  • 自动推导返回类型:C#编译器会根据T和U的原生加法规则自动确定TAddResult,比如int与float相加时,结果类型会被推导为float,符合常规数值运算逻辑。
  • 尺寸校验:所有加法操作前必须验证矩阵宽高一致,避免维度不匹配的错误。
  • 索引器的作用:通过索引器直接访问元素,让加法逻辑更简洁易懂。

使用示例

// 初始化int类型矩阵
var intMatrix = new Matrix<int>(2, 2);
intMatrix[0,0] = 1; intMatrix[0,1] = 2;
intMatrix[1,0] = 3; intMatrix[1,1] = 4;

// 初始化float类型矩阵
var floatMatrix = new Matrix<float>(2, 2);
floatMatrix[0,0] = 1.5f; floatMatrix[0,1] = 2.5f;
floatMatrix[1,0] = 3.5f; floatMatrix[1,1] = 4.5f;

// 自动推导结果为Matrix<float>
Matrix<float> result = intMatrix + floatMatrix;

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.20 01:20:56