从一个方法传递两个数组以从另一个方法C#收集用户信息
本文关键字:方法 另一个 用户 信息 一个 两个 数组 | 更新日期: 2023-09-27 18:23:43
我不是在寻找特定的代码,而是在寻找信息和指导。我想学习,但并不真的希望有人来编码。
我正在研究如何将两个数组传递给不同的方法,以便用用户输入填充它们。我似乎无法理解这一点,我研究了各种网站以及我的文本和讲座,但找不到做到这一点所需的技术。我知道如何将一个数组传递给不同的方法进行处理(IE获取avg/sum等),但不知道如何从一个单独的方法填充两个数组。如有任何指导和信息,我们将不胜感激。这就是我到目前为止所得到的,或者更确切地说,是我剩下的。我已经完成了其他方法,只需要这一部分就可以进入调试阶段。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace PhoneDial
{
class Program
{
// Get player names and their scores and stores them into array for an unknown number of players up to 100
static void InputData(string[] nameList, int[]playerScore)
{
string userInput;
int count = 0;
do
{
Console.Write("'nEnter a players name: ");
userInput = Console.ReadLine();
if (userInput != "Q" && userInput != "q")
{
nameList[0] = Console.ReadLine();
++count;
}
else break;
Console.WriteLine("Enter {0}'s score:", userInput);
playerScore[0] = Convert.ToInt32(Console.ReadLine());
} while (userInput != "Q" && userInput != "q");
}
//Declare variables for number of players and average score and two arrays of size 100 (one for names, one for respective scores
//Calls functions in sequence, passing necessary parameters by reference
//InputData(), passing arrays and number of players variable by reference
//DisplayPlayerData(), passing arrays and number of players by reference
//CalculateAverageScore(), passing arrays and number of players by reference. Store returned value in avg variable
//DisplayBelowAverage(), passing arrays and number of players variable by reference, passing average variable by value
static void Main(string[] args)
{
string[] nameList = new string[100];
int[] playerScore = new int[100];
int count = 0, avg = 0;
InputData(nameList, playerScore);
}
您的问题并不完全清楚,但据我所知,要在一个方法中声明一个数组并传递给另一个要填充的方法,您只需要:
public void MethodA()
{
string[] stringArray = new string[100];
MethodB(stringArray);
}
public void MethodB(string[] stringArray)
{
// Fill the array
stringArray[0] = "Hello";
// ...
}
但是,如果您希望将一些变量引用传递给某个方法,然后让该方法创建数组并填充它,那么您将希望对数组变量使用ref
关键字(与标准变量一样)。像这样:
public void MethodA()
{
string[] stringArray;
MethodB(ref stringArray);
// Array is now created and filled
}
public void MethodB(ref string[] stringArray)
{
// Create the array
stringArray = new string[100];
// Fill the array
stringArray[0] = "Hello";
// ...
}
使用两个数组执行这两种方法中的任何一种都是相同的,只是添加了一个参数。即:
public void MethodB(string[] array1, int[] array2) { }
public void MethodB(ref string[] array1, ref int[] array2) { }
使用字典而不是数组。
Dictionary<string, int> Results = new Dictionary<string, int>();
http://msdn.microsoft.com/en-us/library/x525za90%28v=vs.110%29.aspx
您可以将变量nameList和playerScore放在类Program下,使其全局化{(不要忘记将变量设置为静态并列出它们)。
然后在InputData中使用.add方法向这两个变量添加可选值。
也许使用字典而不是两个数组也是一个好主意。
我希望这对有帮助