我目前正在研究C#中的矩阵实现。这不是一个关于如何......的问题。应该工作还是......类似。它更多的是关于“设计部分”......所以,我想实现一个转换矩阵(http://en.wikipedia.org/wiki/Transpose)的函数。很容易想到,但我真的很难选择,哪种实施方式最优雅。
但首先是矩阵类的一些代码:
namespace Math
{
public class Matrix
{
protected double[,] matrix;
public Matrix(byte m, byte n)[...]
public Matrix(Matrix matrix)[...]
public byte M { get; private set; }
public byte N { get; private set; }
// Possibility 1 (changes the matrix directly)
public void Transpose()[...]
// Possibility 2 (getter method)
public Matrix GetTransposed()[...]
// Possibility 3 (property)
public Matrix TransposedMatrix
{
get[...]
}
// Possibility 4 (static method; a bit like an operator)
public static Matrix Transpose(Matrix matrix)[...]
}
}
在这里,您将如何使用不同的可能性:
namespace MathTest
{
class Program
{
static void Main(string[] args)
{
// Create a new matrix object...
var mat1 = new Math.Matrix(4, 4);
// Using possibility 2 (getter method, like "GetHashCode()" or sth. similar)
var mat2 = mat1.GetTransposed();
// Using possibility 3 (the transposed matrix is a property of each matrix)
var mat3 = mat1.TransposedMatrix;
// Using possibility 4 (definition and use is like an unary operator)
var mat4 = Math.Matrix.Transpose(mat1);
// Using possibility 1 (changes the matrix directly)
mat1.Transpose();
}
}
}
您更喜欢哪种方式?为什么?或者是否有更好的方法来实现矩阵的转置?
非常感谢!
本杰明
答案 0 :(得分:1)
我宁愿投票支持
public Matrix Transpose() { ... }
可能性1
是的,恕我直言,可疑,因为Matrix似乎不可变(所有其他方法都不会改变它)。此外,其他操作(如果您决定实施它们),例如算术+, - ,*,/,也不会改变初始矩阵,它们会返回 new 矩阵。 Matrix B = -A; // <- A doesn't changed
Matrix D = A + B * C; // <- A, B, C don't changed
Matrix E = F.Transpose(); // <- I hope to have F being intact as well
可能性2
是最好的一个;我宁愿将方法从GetTransposed()重命名为Transpose() - 我们通常使用活动名称 - 执行,发送,写入而不是GetPerformed,GetSent等。
// looks better than
// A.GetPerformed().GetValidated().GetSentTo(@"Me@MyServer.com");
A.Perform().Validate().SendTo(@"Me@MyServer.com");
// The same with transpose:
// easier to read than
// A.GetTransposed().GetAppied(x => x * x).GetToString();
A.Transpose().Apply(x => x * x).ToString();
可能性3
我个人不喜欢它,因为TransposedMatrix不是其名称的属性,如RowCount,ColCount,IsUnit,IsDegenrate ......而TransposedMatrix看起来非常类似于< em> functions ,如Exp(),Sqrt()......
A.ColCount; // <- property of the matrix
A.IsDegenerate; // <- another property of the matrix
A.ToString(); // <- is not a property: it's conversion (function) into string representation
A.Sqrt(); // <- is not a property, square root is a function
A.Transpose(); // <- is not a propery either: it's a function too
可能性4:
恕我直言,听起来不自然。我的思维方式是:“我有一个矩阵实例A,我希望有一个转置矩阵,比方说,B,所以我应该用A做一些事情”。我将开始寻找方法: B = A.Transpose();
B = A.ToTransposed();
B = A.GetTransposed();
B = A.Rotate();
B = A.Transform(...);
B = A.DoSomething();
静态方法很好,恕我直言,创建。 e.g。
A = Math.Matrix.Zero(5); // <- Create 5x5 Matrix, all zeroes
B = Math.Matrix.Unit(6); // <- 6x6 unit matrix