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

C#二维矩阵类开发:如何实现矩阵存储与独立打印方法?

解决方案

核心问题是你需要在类中添加实例级的二维数组字段存储矩阵数据,让构造函数只负责初始化和填充数据,打印逻辑抽成独立方法。这里不需要使用ref/out,因为类的实例方法可以直接访问类的字段。

修改后的完整代码

using System;

namespace Vectors_Matrices
{   
    public class Matrices
    {
        // 私有字段存储矩阵数据,封装维度为只读属性
        private int[,] _matrix;
        public int Rows { get; }
        public int Columns { get; }

        public Matrices()
        {
            Console.WriteLine("Matrices constructor created...");
        }

        // 创建方阵的构造函数,复用指定维度构造逻辑
        public Matrices(int size) : this(size, size)
        {
        }

        // 创建指定维度矩阵并接收用户输入的构造函数
        public Matrices(int rows, int columns)
        {
            Rows = rows;
            Columns = columns;
            _matrix = new int[rows, columns];

            Console.WriteLine("2D Matrix created with [{0}, {1}] dimensions", rows, columns);
            // 填充矩阵数据
            for (int i = 0; i < rows; i++)
            {
                for (int j = 0; j < columns; j++)
                {
                    Console.Write("Array Index [{0}, {1}]: ", i, j);
                    _matrix[i, j] = Convert.ToInt32(Console.ReadLine());
                }
            }
        }

        // 独立的矩阵打印方法
        public void Print()
        {
            for (int i = 0; i < Rows; i++)
            {
                for (int j = 0; j < Columns; j++)
                {
                    Console.Write(j == 0 ? $"{_matrix[i, j]}" : $" {_matrix[i, j]}");
                }
                Console.WriteLine();
            }
        }
    }

    public class Program
    {
        public static void Main(string[] args)
        {
            Console.Write("Insert your row count for the 2D matrix: ");
            int rows = Convert.ToInt32(Console.ReadLine());
            Console.Write("Insert your column count for the 2D matrix: ");
            int columns = Convert.ToInt32(Console.ReadLine());

            Matrices my2DMatrix = new Matrices(rows, columns);
            // 按需调用打印方法
            Console.WriteLine("\nPrinting your matrix:");
            my2DMatrix.Print();
        }
    }
}

关键改动说明

  • 添加实例存储字段:新增private int[,] _matrix,作为类的实例字段,所有实例方法(如Print())可直接访问,无需ref/out——对象生命周期内该字段会持续保存数据。
  • 封装维度属性:将原公开的x/y字段替换为只读属性Rows和Columns,符合C#封装原则,避免外部随意修改矩阵维度。
  • 分离构造与打印逻辑:构造函数仅负责初始化矩阵、接收用户输入填充数据;打印逻辑移至独立的Print()方法,需要打印时调用即可。
  • 构造函数复用:方阵构造函数通过: this(size, size)复用指定维度的构造逻辑,减少代码冗余。

额外实现思路

1. 支持直接传入矩阵数据的构造函数

若无需用户输入,直接用已有数组创建矩阵,可添加重载构造函数:

public Matrices(int[,] existingMatrix)
{
    Rows = existingMatrix.GetLength(0);
    Columns = existingMatrix.GetLength(1);
    // 深拷贝避免外部修改影响内部数据
    _matrix = new int[Rows, Columns];
    Array.Copy(existingMatrix, _matrix, existingMatrix.Length);
}

2. 静态方法封装用户输入逻辑

将用户输入的逻辑抽成静态方法,让构造函数更专注于初始化:

public static Matrices CreateFromUserInput()
{
    Console.Write("Insert row count: ");
    int rows = Convert.ToInt32(Console.ReadLine());
    Console.Write("Insert column count: ");
    int columns = Convert.ToInt32(Console.ReadLine());

    return new Matrices(rows, columns);
}

在Main中调用:Matrices myMatrix = Matrices.CreateFromUserInput();

3. 线性运算拓展基础

后续要实现加法、乘法等运算,可添加对应方法示例:

public Matrices Add(Matrices other)
{
    if (Rows != other.Rows || Columns != other.Columns)
        throw new ArgumentException("Matrices must have same dimensions for addition");
    
    var result = new Matrices(Rows, Columns);
    for (int i = 0; i < Rows; i++)
    {
        for (int j = 0; j < Columns; j++)
        {
            result._matrix[i, j] = _matrix[i, j] + other._matrix[i, j];
        }
    }
    return result;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 02:30:47