C# 在C中为列表定义运算符#
我想为C#中的列表定义一些操作。 例如,加法(+)和转置(')。 但是,在编译代码时出现了错误。 我定义了一个从List>继承的矩阵类。 此外,我实现了+和'操作符。 第一个是好的,但是当我主要调用它时,会出现错误。 第二个方法甚至无法编译。 有人能帮忙吗? 非常感谢C# 在C中为列表定义运算符#,c#,matrix,operator-keyword,C#,Matrix,Operator Keyword,我想为C#中的列表定义一些操作。 例如,加法(+)和转置(')。 但是,在编译代码时出现了错误。 我定义了一个从List>继承的矩阵类。 此外,我实现了+和'操作符。 第一个是好的,但是当我主要调用它时,会出现错误。 第二个方法甚至无法编译。 有人能帮忙吗? 非常感谢 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace test
{
class Matrix : List<List<double>>
{
public static Matrix operator +(Matrix a, Matrix b)
{
Matrix c = new Matrix();
int i, j;
for (i = 0; i < a.Count; i++)
{
for (j = 0; j < a[1].Count; j++)
{
c[i][j] = a[i][j] + b[i][j];
}
}
return c;
}
public static Matrix operator ' (Matrix a)
{
Matrix b = new Matrix();
int i, j;
for (i = 0; i<a.Count; i++)
{
for (j = 0; j < a[1].Count; j++)
{
b[j][i] = a[j][i];
}
}
return b;
}
public static int Main(string[] args)
{
Matrix x = new Matrix { new List<double> { 1, 2, 5, 2 }, new List<double> { 3, 4, 0, 7 } };
Matrix y = new Matrix { new List<double> { 1, 2, 5, 2 }, new List<double> { 3, 4, 0, 7 } };
Matrix z = new Matrix();
z = x + y;
Console.WriteLine(z);
return 0;
}
}
}
使用系统;
使用System.Collections.Generic;
使用System.Linq;
使用系统文本;
使用System.Threading.Tasks;
名称空间测试
{
类别矩阵:列表
{
公共静态矩阵运算符+(矩阵a、矩阵b)
{
矩阵c=新矩阵();
int i,j;
对于(i=0;i for(i=0;i)不是有效的运算符。可重载运算符为:
一元:+-!~++-真-假
二进制:+-*/%和| ^>=!=<>=
其中一些也有限制。例如,比较运算符必须成对重载,移位运算符(>)的第二个参数必须是int
看看:你不能选择“过载”任何您想要的任意符号。没有像“
这样的运算符。您会遇到什么错误?您遇到的确切问题是什么?这是一个可重载运算符的列表。这是重载运算符的教程-您不为新矩阵c分配任何空间。好的,让我们先忽略“方法”。如何更正中的错误“+”?矩阵x=新矩阵{new List{1,2,5,2},新列表{3,4,0,7};矩阵y=新矩阵{new List{1,2,5,2},新列表{3,4,0,7};矩阵z=新矩阵();z=x+y;@Frankie矩阵c=新矩阵()
将创建一个空矩阵。它不包含内部列表。这就是为什么在c[i][j]=a[i][j]+b[i][j]行上会出现ArgumentOutOfRangeException
的原因;
我将其更改为:矩阵x=新矩阵{new List{1,2,5,2},new List{3,4,0,7};矩阵y=新矩阵{new List}{1,2,5,2},新列表{3,4,0,7};矩阵z=新矩阵{新列表{1,2,5,2},新列表{3,4,0,7};z=x+y;但是错误也会发生。Matrix z=new…
完全没有用。您在下一行中给了z另一个值。只需将其设置为Matrix z=x+y;
但问题在于运算符+方法。