这是一个关于方法的非常简单的问题。我是 C# 的新手,正在测试列表。我如何调用方法“addTwo”以便它以两个为单位更新“标记”列表中的每个元素?请注意,我已经创建了这个方法(向下滚动到主要方法下方)。我只想知道如何在 main 方法中调用它。
namespace ParallelLists
{
class Program
{
static void Main(string[] args)
{
//create an list of 4 student names
List<string> names = new List<string>(4);
names.Add("Matt");
names.Add("Mark");
names.Add("Luke");
names.Add("John");
//create a list of 4 integers representing marks
List<decimal> marks = new List<decimal>(4);
marks.Add(88m);
marks.Add(90m);
marks.Add(55m);
marks.Add(75m);
Console.WriteLine("the mark of " + names[0] + " is : " + marks[0]);
Console.ReadLine();
//Upgrade everyone by 2 marks
...
}
public List<decimal> addTwo(List<decimal> mark)
{
List<decimal> temp = mark;
for (int i = 0; i < temp.Count; i++)
{
temp[i] += 2m;
}
return temp;
}
}
}
请您参考如下方法:
你需要让你的方法静态化,因为你正在访问一个非对象。您还需要使用返回值更新标记集合。您实际上不需要返回列表,因为列表是可变的。
class Program
{
static void Main(string[] args)
{
//create an list of 4 student names
List<string> names = new List<string>(4);
names.Add("Matt");
names.Add("Mark");
names.Add("Luke");
names.Add("John");
//create a list of 4 integers representing marks
List<decimal> marks = new List<decimal>(4);
marks.Add(88m);
marks.Add(90m);
marks.Add(55m);
marks.Add(75m);
marks = addTwo(marks);
Console.WriteLine("the mark of " + names[0] + " is : " + marks[0]);
Console.ReadLine();
Console.Read();
}
public static List<decimal> addTwo(List<decimal> mark)
{
List<decimal> temp = mark;
for (int i = 0; i < temp.Count; i++)
{
temp[i] += 2m;
}
return temp;
}
}
如果您不想返回列表,您可以执行以下操作:
class Program
{
static void Main(string[] args)
{
//create an list of 4 student names
List<string> names = new List<string>(4);
names.Add("Matt");
names.Add("Mark");
names.Add("Luke");
names.Add("John");
//create a list of 4 integers representing marks
List<decimal> marks = new List<decimal>(4);
marks.Add(88m);
marks.Add(90m);
marks.Add(55m);
marks.Add(75m);
addTwo(marks);
Console.WriteLine("the mark of " + names[0] + " is : " + marks[0]);
Console.ReadLine();
Console.Read();
}
public static void addTwo(List<decimal> mark)
{
List<decimal> temp = mark;
for (int i = 0; i < temp.Count; i++)
{
temp[i] += 2m;
}
}
}
