包括如下成员:
私有字段mintLl),矩阵类用二维整型数组m表示矩阵元素,矩阵的行数rowint),矩阵的列数colin).
上述字段的公有属性Row. Col分别获取矩阵的行数和列数。
构造方法里通过传两个int类型的参数来指定矩阵的行列,并用这一大小来初始化数组m.使用-10-10之间的随机数对数组m初始化
索引器输出矩阵的中的给定行列值返回元素值,假如行列值参数越界,抛出异常“行列值越界”
重写ToString可以按行列的形式输出矩阵元素。
题主要的代码如下
using System;
namespace ConsoleApp1
{
class Matrix
{
private int[,] m;
private int row;
private int col;
public int Row { get { return row; } set { row = value; } }
public int Col { get { return col; } set { col = value; } }
public Matrix(int row, int col)
{
this.row = row;
this.col = col;
m = new int[row, col];
var rnd = new Random();
for(var i = 0; i < row; i++)
{
for (var j = 0; j < col; j++)
m[i, j] = rnd.Next(-10, 11);
}
}
public new string ToString()
{
string s = "";
for (var i = 0; i < row; i++)
{
for (var j = 0; j < col; j++)
s +=string.Format("{0,4}", m[i, j])+" ";
s += "\n";
}
return s;
}
public int this[int row, int col]
{
get
{
if (row >= this.row || col >= this.col) throw new Exception("行列值越界");
return m[row, col];
}
}
}
class Program
{
static void Main(string[] args)
{
var m = new Matrix(5, 5);
Console.Write(m.ToString());
Console.WriteLine(m[2, 3]);
try
{
Console.WriteLine(m[3, 5]);//出错
}
catch (Exception e) { Console.WriteLine(e.Message); }
Console.ReadKey();
}
}
}
有帮助麻烦点下【采纳该答案】~~