【发布时间】:2014-07-02 09:24:15
【问题描述】:
我正在尝试使用动态数学运算符处理二维数组。
这是有问题的方法:
public float[,] Calculate(int[,] a, int[,] b, Func<int,int,float> compute)
{
int columns = a.GetLength(0);
int rows = a.GetLength(1);
float[,] result = new float[columns,rows];
for(int i = 0; i < columns; i++)
{
for(int j = 0; j < rows; j++)
{
result[i,j] = compute(a[i,j], b[i,j]);
}
}
return result;
}
这个方法是这样调用的:
int[,] a = new int[2,3] { {2, 6, 19}, {3, -4, 25}};
int[,] b = new int[2,3] { {12, -2, 11}, {1, -11, 0}};
//1
float[,] c = Calculate(a, b, (x,y) => (x+y));
//2
float[,] c = Calculate(a, b, (x,y) => (x-y));
//3
float[,] c = Calculate(a, b, (x,y) => (x*y));
//4
float[,] c = Calculate(a, b, (x,y) => (x/y));
现在,虽然版本 1 到 3 可以完美运行,但版本 4 迟早会抛出异常。 现在解决这个问题的一种方法是使用 try catch 块:
try
{
result[i,j] = compute(a[i,j], b[i,j]);
}
catch(DivideByZeroException ex)
{
result[i,j] = 0;
}
这看起来像我使用 try catch 进行流量控制,我宁愿避免它(另外,结果是错误的)。有没有办法在函数调用中检查除法运算符,如果运算符是/,检查第二个数组是否包含0并返回null?
【问题讨论】:
-
请记住,这将导致整数除法,因此 5/2 等于 2 而不是 2.5。您需要将至少一个参数转换为浮点数以获取实数(浮点数)。
-
只要让
Calculate抛出异常并在调用者(或调用者的调用者)中处理即可。 -
“仅返回 null”是否意味着您打算更改函数签名以现在返回
float?[,]?如果是这样,我们可以将compute的定义更改为<int,int,float?>。如果是这样,我们是否可以不让compute决定其参数是否有意义并决定何时返回null? -
@Damien_The_Unbeliever Just Yes - 你可以/可能。
标签: c# func divide-by-zero