我在我的应用程序中使用自定义Matrix类,我经常添加多个矩阵:
Matrix result = a + b + c + d; // a, b, c and d are also Matrices
但是,这为每个加法操作创建了一个中间矩阵.由于这是简单的添加,因此可以通过一次添加所有4个矩阵的元素来避免中间对象并创建结果.我怎么能做到这一点?
注:我知道我可以这样定义多种功能Add3Matrices(a, b, c)
,Add4Matrices(a, b, c, d)
等,但我想保持的优美result = a + b + c + d
.
您可以通过使用延迟评估将自己限制为单个小中间件.就像是
public class LazyMatrix { public static implicit operator Matrix(LazyMatrix l) { Matrix m = new Matrix(); foreach (Matrix x in l.Pending) { for (int i = 0; i < 2; ++i) for (int j = 0; j < 2; ++j) m.Contents[i, j] += x.Contents[i, j]; } return m; } public ListPending = new List (); } public class Matrix { public int[,] Contents = { { 0, 0 }, { 0, 0 } }; public static LazyMatrix operator+(Matrix a, Matrix b) { LazyMatrix l = new LazyMatrix(); l.Pending.Add(a); l.Pending.Add(b); return l; } public static LazyMatrix operator+(Matrix a, LazyMatrix b) { b.Pending.Add(a); return b; } } class Program { static void Main(string[] args) { Matrix a = new Matrix(); Matrix b = new Matrix(); Matrix c = new Matrix(); Matrix d = new Matrix(); a.Contents[0, 0] = 1; b.Contents[1, 0] = 4; c.Contents[0, 1] = 9; d.Contents[1, 1] = 16; Matrix m = a + b + c + d; for (int i = 0; i < 2; ++i) { for (int j = 0; j < 2; ++j) { System.Console.Write(m.Contents[i, j]); System.Console.Write(" "); } System.Console.WriteLine(); } System.Console.ReadLine(); } }