【问题标题】:Passing in a portion of a multidimensional array as argument in C#在 C# 中将多维数组的一部分作为参数传递
【发布时间】:2020-10-02 21:36:26
【问题描述】:

需要将一些c++代码转换成c#。在这种情况下,我需要将多维数组的第二维传递给函数 dot(...)。

这是原来的c++声明/*和定义*/,后跟全局静态const数组。

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 );
    }
}

【问题讨论】:

标签: c# multidimensional-array arguments


【解决方案1】:

您可以在不使用 ref 的情况下传递数组的一部分。

我建议的示例不是多维数组,而是一个锯齿状数组,它是一个数组数组

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}
};

交错数组与多维数组的比较:

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;
}

【讨论】:

  • 为什么不经常使用多维数组有什么具体原因,应该避免吗?
  • 为了解决这种泛化问题,我不怎么使用它们,因为使用锯齿状数组更方便,速度更快,而且它们对我来说似乎更直观,请参阅我更新的代码示例.
  • 数组不是通过引用传递的,ref 也不是多余的。变量的值是一个引用,这与通过引用传递有很大不同。此外,不使用多维数组的断言是不正确的,它们被大量使用。您个人可能不会使用它们,但这不是一回事。
  • @Servy 我修正了我不经常使用它们的声明,并且我发现它们更直观地使用,你刚刚阅读我的评论吗?
  • @Servy 另外,数组是引用类型,引用类型总是通过引用传递。我知道当然会传递引用的值。但一般来说,每个人都使用引用传递这个术语。
猜你喜欢
  • 2022-01-09
  • 2012-11-24
  • 2010-09-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多