【发布时间】:2019-07-07 22:34:55
【问题描述】:
我正在使用矩阵并且有问题如何正确初始化不同的二维对象数组,当它们的类型取决于条件(如果其他)。如果我在 if else 之前声明了矩阵及其类型,那么我不能在里面声明不同的类型。如果我在 if else 中声明它,它就不存在于范围之外。
在 Stack Overflow 上已经有类似的问题,我找到了一些解决此问题的方法。
- 将所有方法(即使没有重载 - 对两种类型执行完全相同的方法)都放在 if else 中。 -> 这可行,但代码重复。
- 制作通用接口。 -> 方法不适用于 ICell,我无法弄清楚将 ICell[][] 重新输入到 CellA[][]。
- 将矩阵声明为变量数组的数组。 -> 无法弄清楚这是如何工作的。
还有其他选择吗?最好的解决方案是什么?还是我的方法完全错误?
谢谢
附:代码很长,这是简化版。
class CellA : IComparable {
// 2 attributes
//constructor 1 param
public int CompareTo(object obj) {
//code
}
}
class CellB : CellA {
// 3 attributes
//constructor 2 params
}
class Program {
static void Main(string[] args) {
data[0] = "...";
...
data[x] = "...";
//user input own data or chooses data set
...
bool mode = true/false; //user chooses computing mode
if (mode) {
CellA[][] matrix = InitializeMatrixA(data[indexOfSet]);
} else {
CellB[][] matrix = InitializeMatrixB(data[indexOfSet]);
}
DoSomethingOther(ref matrix);
//several ref matrix manipulation methods
Console.WriteLine(DoSomethingSame(matrix));
}
static CellA[][] InitializeMatrixA(string data) {
//string processing, not important
CellA[][] matrix = new CellA[9][];
for (int i = 0; i < 9; i++) {
matrix[i] = new Cell[9];
for (int j = 0; j < 9; j++) {
matrix[i][j] = new CellA(stringPart[i*9+j]);
}
}
return matrix;
}
static CellB[][] InitializeMatrixB(string data) {
//different string processing, not important
CellB[][] matrix = new CellB[9][];
for (int i = 0; i < 9; i++) {
matrix[i] = new Cell[9];
for (int j = 0; j < 9; j++) {
matrix[i][j] = new CellA(stringPart[i*18+j*2], stringPart[i*18+j*2+1]);
}
}
return matrix;
}
//same function for As and Bs
static int DoSomethingSame(ref CellA[][] matrix) { //code }
//many different overloaded methods all working with reference to "matrix", slightly different computing for As and Bs
static void DoSomethingOther(ref CellA[][] matrix) { //code }
static void DoSomethingOther(ref CellB[][] matrix) { // slightly different code}
【问题讨论】:
-
您对
DoSomethingOther(...)对CellB的“代码略有不同”评论是否表明存在通用接口?也就是说,您的CellB派生自CellA,因此矩阵可以只是CellA[][],但填充有CellA或CellB。 -
在计算中使用2个或3个参数是不同的,但有些部分是完全一样的。
-
但是是的,该方法是否可以只有一个,并且在 if (type is CellA) {} else {}
标签: c# class object multidimensional-array types