简体   繁体   English

将数组传递给方法

[英]Passing arrays to methods

Even though all variables are arrays I seem to be getting errors stating that conversion from string to string[] variables is not possible. 即使所有变量都是数组,我似乎也收到错误消息,指出无法将字符串转换为string []变量。

class Program
{

    private static int[] testKey = { 10, 12, 15, 18, 2, 1, 200 };
    private static string[] testVar1 = { "hello", "albert", "france", "john", "version", "zebra" };
    private static string[] testVar2 = { "helllllllo", "jordan", "land", "Hobart", "Hogwarts", "hamburger", "Code" };

    static void Main(string[] args)
    {
        for (int currentLineCount = 0; currentLineCount < 233; currentLineCount++)
        {
            OrderAZ(testKey[currentLineCount], testVar1[currentLineCount], testVar2[currentLineCount]);
        }
        //Argument 3: cannot convert from 'string' to 'string[]'
        //Argument 2: cannot convert from 'string' to 'string[]'
        //Argument 1: cannot convert from 'int' to 'int[]'
    }

    public static void OrderAZ(int[] sortKey, string[] sortVariableTwo, string[] sortVariableOne)
    {
       //sort method stub
    }
}

testKey is an array of int , but testKey[currentLineCount] is an int . testKey是一个int数组,而testKey[currentLineCount]是一个int The OrderAZ method expects a int[] , not an int (and similarly for the other parameters). OrderAZ方法需要一个int[] ,而不是一个int (对于其他参数也是如此)。 You need to either pass an array, or change the signature of your OrderAZ method to accept an int (hard to tell without knowing what your code is supposed to do). 您需要传递一个数组,或更改OrderAZ方法的签名以接受一个int (很难知道,代码不应该做什么)。

if you want send a string as an array you may need to use a string method to convert it in to a string array such a string.split() , a string is not an array of strings as a int is not an array of int till you convert them in to it somehow. 如果要发送字符串作为数组,则可能需要使用字符串方法将其转换为字符串数组,例如string.split() ,字符串不是字符串数组,因为int不是int数组直到您以某种方式将它们转换成它。

In this case you are sending ítems of the array and an ítem of an array of strings is actually a string, so your method has to recieve a string, but if you want to send the whole array then remove the whole brackets part on the call, for example: 在这种情况下,您要发送数组的-tem,而字符串数组的-tem实际上是一个字符串,因此您的方法必须接收一个字符串,但是如果要发送整个数组,则请删除调用中的整个方括号部分, 例如:

OrderAZ(testKey, testVar1, ...);

Then you can keep your method as it is. 然后,您可以保持原样。 Good luck! 祝好运!

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

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