【问题标题】:Use variable from Main method in another method在另一个方法中使用 Main 方法中的变量
【发布时间】:2014-10-13 10:01:39
【问题描述】:

我目前正在执行一项任务,只是想在某事上得到一点帮助。对于我的代码,我必须从一组值中找到最低和最高值,然后将那些不是最高或最低的值加在一起(例如,1、2、3、4、5 --- 我会加 2+ 3+4)

所以我认为最好的方法是遍历数组并记录存储最高/最低值的位置。这就是我的问题所在,数组存储在Main方法中,我还没有找到在其他方法中访问它的方法。到目前为止我的代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Scoring {
class Program {   
    static void Main(string[] args) {
        int[] scores = { 4, 7, 9, 3, 8, 6 };

        find_Low();

        ExitProgram();
    }

    static int find_Low() {
        int low = int.MaxValue;
        int low_index = -1;


        foreach (int i in scores) {

            if (scores[i] < low) {
                low = scores[i];
                low_index = i;

            }                
        }

        Console.WriteLine(low);
        Console.WriteLine(low_index);
        return low;  
    }

    static void ExitProgram() {
        Console.Write("\n\nPress any key to exit program: ");
        Console.ReadKey();
    }//end ExitProgram
}

}

我得到的错误是“名称'scores'在当前上下文中不存在。任何提示/帮助将不胜感激。

【问题讨论】:

标签: c# variables methods main


【解决方案1】:

为使其尽可能简单,请像这样更改您的程序

class Program {

    static int[] scores = { 4, 7, 9, 3, 8, 6 };

    static void Main(string[] args) { ...}
}

【讨论】:

  • 如果你想从静态方法访问分数变量,它必须是静态的。此外,使用参数几乎总是比使用静态字段更好。
  • 对了,忘记加静态了。当然参数更好,但我的目标是用最简单的方法解决他的问题,以避免更多的混乱......
【解决方案2】:

您可以将数组作为参数传递给函数:

using System.IO;
using System.Linq;
using System;

class Program
{
    static void Main()
    {
        int[] scores = { 4, 7, 9, 3, 8, 6 };
        Console.WriteLine(resoult(scores));
    }

    static int resoult(int[] pScores)
    {
        return pScores.Sum() - pScores.Max() - pScores.Min();
    }
}

【讨论】:

  • 谢谢,我解决问题的思路大致相同,只是不知道如何在新方法中使用变量。最后一个问题,为什么在方法声明中将分数重命名为 pScores?如果不重命名它会不会工作?谢谢
  • 这只是一个命名约定。他们可以共享相同的名称“分数”。
  • @user3496101 如果您找到对您有帮助的答案。选择它作为关闭问题的答案。
【解决方案3】:

将您的数组作为参数传递:

static int find_Low(int[] scores) { 
     //your code
    }

在主方法中:

static void Main(string[] args) {
    int[] scores = { 4, 7, 9, 3, 8, 6 };

    find_Low(scores);    //pass array

    ExitProgram();
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-02-03
    • 1970-01-01
    • 1970-01-01
    • 2020-04-24
    • 2013-10-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多