简体   繁体   English

如何在C#中传递通用数组?

[英]How to pass a generic array in C#?

I need to pass an array to a function in C# where the array may be a string[], int[], or double[] and may be 1 to multiple dimensions. 我需要将数组传递给C#中的函数,其中数组可能是string [],int []或double [],并且可能是1到多维。

Reasoning: 推理:

I am needing to pass an array to a function to calculate its length, similar to: 我需要将数组传递给函数以计算其长度,类似于:

public int getLength(array[] someArray, int dimension)
{
   if(dimension > 0) //get length of dimension 
     return someArray.getLength(dimension);
   else //get length of entire array
     return someArray.Length;
}

Question: 题:

How can I pass a generic array? 如何传递通用数组?

Or 要么

Is there a better way to do this - say convert the array to a List? 有没有更好的方法来执行此操作-例如将数组转换为列表?

For the purpose you cite, just pass Array someArray - that should be fine, and covers any number of dimensions. 出于您的目的,只需传递Array someArray应该没问题,可以覆盖任意数量的尺寸。 For a vector (a 1-dimensional, 0-based array), you can use generics ( GetLength<T>(T[] someArray) ) - but that seems pointless when for a vector .Length is more convenient. 对于矢量 (一维的,基于0阵列),则可以使用泛型( GetLength<T>(T[] someArray) -但似乎并没有用于向量.Length是更方便。

But for an unknown number of dimensions (or for a non-vector single-dimensional array), you are limited to Array . 但是对于未知数量的维(或非矢量单维数组),您将被限制为Array

如果要使用ArrayList List的属性,还可以使用ArrayList ,该ArrayList可容纳任意数量的object

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM