在 C# 中将多维数组的一部分作为参数传递
Passing in a portion of a multidimensional array as argument in C#
需要将一些 C++ 代码转换成 C#。在这种情况下,我需要将多维数组的第二维传递给函数 dot(...).
这是原始的c++声明/*和定义*/,后面是全局静态常量数组。
double dot( const int* g, const double x, const double y ) /*{ return g[0]*x + g[1]*y; }*/;
static const int grad3[ 12 ][ 3 ] = {...};
在 c# 中可能是这样的:
public class TestClass
{
float dot( ref int[] g, float x, float y ) { return g[0] * x + g[1] * y; }
public static readonly int[,] grad3 = new int[12, 3]{...};
}
这里是一个例子,看看应该如何访问它:
public class TestClass
{
...
void test()
{
int gi0 = 0;
double d1 = dot( grad3[ gi0 ], x0, y0, z0 );
}
}
您可以在不使用 ref
的情况下传递数组的一部分。
我建议的示例不是 multi-dimensional 数组,而是一个锯齿状数组,它是一个 数组的数组 。
public class TestClass
{
public static float Dot(int[] g, float x, float y)
{
return g[0] * x + g[1] * y;
}
// Note that the second index is empty
public static readonly int[][] grad3 = new int[12][] {...};
}
您可以像这样传递多维数组(锯齿状数组):
var value = TestClass.grad3;
TestClass.Dot(value[0], x0, y0, z0);
此外,初始化语法是这样的:
public static readonly int[][] TwoDimArray = new int[3][]
{
new[] {1, 2, 3},
new[] {4, 5, 6},
new[] {8, 9, 10}
};
交错数组与multi-dimensional数组的比较:
public static double Sum(double[,] d) {
double sum = 0;
int l1 = d.GetLength(0);
int l2 = d.GetLength(1);
for (int i = 0; i < l1; ++i)
for (int j = 0; j < l2; ++j)
sum += d[i, j];
return sum;
}
// This is intuitive and clear for me
public static double Sum(double[][] d) {
double sum = 0;
for (int i = 0; i < d.Length; ++i)
for (int j = 0; j < d[i].Length; ++j)
sum += d[i][j];
return sum;
}
需要将一些 C++ 代码转换成 C#。在这种情况下,我需要将多维数组的第二维传递给函数 dot(...).
这是原始的c++声明/*和定义*/,后面是全局静态常量数组。
double dot( const int* g, const double x, const double y ) /*{ return g[0]*x + g[1]*y; }*/;
static const int grad3[ 12 ][ 3 ] = {...};
在 c# 中可能是这样的:
public class TestClass
{
float dot( ref int[] g, float x, float y ) { return g[0] * x + g[1] * y; }
public static readonly int[,] grad3 = new int[12, 3]{...};
}
这里是一个例子,看看应该如何访问它:
public class TestClass
{
...
void test()
{
int gi0 = 0;
double d1 = dot( grad3[ gi0 ], x0, y0, z0 );
}
}
您可以在不使用 ref
的情况下传递数组的一部分。
我建议的示例不是 multi-dimensional 数组,而是一个锯齿状数组,它是一个 数组的数组 。
public class TestClass
{
public static float Dot(int[] g, float x, float y)
{
return g[0] * x + g[1] * y;
}
// Note that the second index is empty
public static readonly int[][] grad3 = new int[12][] {...};
}
您可以像这样传递多维数组(锯齿状数组):
var value = TestClass.grad3;
TestClass.Dot(value[0], x0, y0, z0);
此外,初始化语法是这样的:
public static readonly int[][] TwoDimArray = new int[3][]
{
new[] {1, 2, 3},
new[] {4, 5, 6},
new[] {8, 9, 10}
};
交错数组与multi-dimensional数组的比较:
public static double Sum(double[,] d) {
double sum = 0;
int l1 = d.GetLength(0);
int l2 = d.GetLength(1);
for (int i = 0; i < l1; ++i)
for (int j = 0; j < l2; ++j)
sum += d[i, j];
return sum;
}
// This is intuitive and clear for me
public static double Sum(double[][] d) {
double sum = 0;
for (int i = 0; i < d.Length; ++i)
for (int j = 0; j < d[i].Length; ++j)
sum += d[i][j];
return sum;
}