在C#中带有数组参数 [英] Passing Arrays as Parameters in C#

查看:105
本文介绍了在C#中带有数组参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个接受5的整数,它们保持在一个数组,然后通过该数组返回到主函数。我曾纠结于它几个小时,读了一些MSDN文档就可以了,但它并没有点击。是否有人可以提供一些线索,以什么我做错了什么? 错误: 并非所有的code路径返回一个值; 一些有关的参数无效:

I am trying to create a function that accepts 5 integers, holds them in an array and then passes that array back to the main. I have wrestled with it for a couple of hours and read some MSDN docs on it, but it hasn't "clicked". Can someone please shed some light as to what I am doing wrong? Errors: Not all code paths return a value; something about invalid arguments:

code:

using System;
using System.IO;
using System.Text;

namespace ANumArrayAPP
{
class Program
{
    static void Main()
    {
        int[] i = new int[5];
        ReadInNum(i);

        for (int a = 0; a < 5; a++)
        {
            Console.Write(a);
        }
    }

    static int ReadInNum(int readIn)
    {
        int[] readInn = new int[5];

        for (int i = 0; i < 5; i++)
        {
            Console.WriteLine("Please enter an interger");
            readInn[i] = Console.Read();
        }
    }
}

}

推荐答案

参数为 ReadInNum 是一个 INT ,但你想传递一个数组。你必须使参数匹配你想传递什么,例如:

The parameter to ReadInNum is a single int, but you're trying to pass an array. You have to make the parameter match what you're trying to pass in. For example:

static void ReadInNum(int[] readIn)
{
    for (int i = 0; i < readIn.Length; i++)
    {
        Console.WriteLine("Please enter an interger");
        readIn[i] = int.Parse(Console.ReadLine());
    }
}

这将填补你传递给方法的数组。另一种方法是通过在你要多少整数,并返回数组的的方法:

That will fill the array you pass into the method. Another alternative is to pass in how many integers you want, and return the array from the method:

static int[] ReadInNum(int count)
{
    int[] values = new int[count];
    for (int i = 0; i < count; i++)
    {
        Console.WriteLine("Please enter an interger");
        values[i] = int.Parse(Console.ReadLine());
    }
    return values;
}

您会打电话来这从是这样的:

You'd call this from Main like this:

int[] input = ReadInNum(5);
for (int a = 0; a < 5; a++)
{
    Console.Write(input[a]);
}

这篇关于在C#中带有数组参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆