为了账号安全,请及时绑定邮箱和手机立即绑定

从函数访问数组整数

从函数访问数组整数

C#
SMILET 2022-11-21 17:01:21
我正在尝试在函数中写入数组中的整数,它总是显示“当前上下文中不存在名称'(数组名称)'”int counter = int.Parse(Console.ReadLine()); int[] nums = new int[counter];while (counter > 0){    nums[counter] = counter;    counter--; } (基本上创建了一个长度为用户选择的数组,并将数字从 1 到数组中的计数器) 在一些更改数组整数中的内容的代码之后 (计数器不会更改)print(counter);我创建的一个函数public static void print(int count);{    *some code*    while (count > 0)    {        Console.WriteLine(nums[count]); //line with the error        count--;    } }我期待它在 nums 数组中写入整数,但它没有。(顺便说一句,我需要把它写在函数里面,我稍后在代码中调用它)
查看完整描述

2 回答

?
茅侃侃

TA贡献1842条经验 获得超21个赞

好吧,这意味着您的数组不在函数的上下文中,因此它无法“看到”它。您要么必须在函数中声明它,要么通过类中的某个字段访问它,要么将其作为参数传递

public static void print(int[] nums, int count)、
{...}


查看完整回答
反对 回复 2022-11-21
?
桃花长相依

TA贡献1860条经验 获得超8个赞

“名称‘(数组名称)’在当前上下文中不存在”


由于错误表明您的函数无法在函数上下文中找到数组(因为它在函数本身之外)。


为了找到它,您有两种选择:


print(counter, nums)

public static void print(int count, int[] nums)

{...}

或者将所有内容包装在一个类中:


class Program

{

    static int[] nums; 

    static void Main(string[] args)

    {

        int counter = int.Parse(Console.ReadLine());

        int[] nums = new int[counter];

        while (counter > 0)

        {

            nums[counter] = counter;

            counter--;

        }

        print(counter);

    }

    public static void print(int count)

    {

        // some code

        while (count > 0)

        {

            Console.WriteLine(nums[count]); //line with the error

            count--;

        }

    }

}


查看完整回答
反对 回复 2022-11-21
  • 2 回答
  • 0 关注
  • 85 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号