我将代码输入到列表中。但是,当我尝试在方法调用中迭代代码时,没有返回任何内容。
问题代码可以在"公共类迭代"中找到。我不确定为什么它不会执行。
基本上,我希望有人输入信息。输入信息后,我希望用户通过方法调用遍历列表。
using System;
using System.Text.RegularExpressions;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
public class Iterating
{
List<String> employees = new List<String>();
public void Test2()
{
//This is where I am trying to iterate//
for (int i = 0; i < employees.Count; i++)
{
Console.WriteLine(employees[i]);
}
}
}
public class Testing
{
public void Test1()
{
while (true)
{
List<String> employees = new List<String>();
Regex regex = new Regex(@"((.{5})-\d{2,5}-\d{2,5})|(@.*.com)");
Console.WriteLine("Please enter an e-mail");
string input = Console.ReadLine();
if(string.Equals(input, "quit", StringComparison.OrdinalIgnoreCase))
{
Console.WriteLine("You have quit the program");
break;
}
else if (match.Success)
{
Console.WriteLine(match.Value);
employees.Add(match.Value);
}
}
}
}
public class Program
{
public static void Main()
{
Testing T1 = new Testing();
T1.Test1();
Iterating I1 = new Iterating();
I1.Test2();
}
}
答案 0 :(得分:1)
自
以来你没有得到任何输出employees
列表。employees
列表 - 每个班级都有自己独立的列表
如果希望迭代类打印列表的内容,则需要将其传递给相关列表。 部分示例:
public class Program {
public static void Main() {
List<String> employees = new List<String>();
Testing T1 = new Testing();
T1.Test1(employees);
Iterating I1 = new Iterating();
I1.Test2(employees);
}
}
您可以修改测试方法以使用传递的列表而不是创建新的
答案 1 :(得分:0)
public class Iterating { List<String> employees = new List<String>(); public void Test2() { //This is where I am trying to iterate// for (int i = 0; i < employees.Count; i++) { Console.WriteLine(employees[i]); } } }
员工总是空着的,因为这与Testing.employees没有任何关系,你可能想要删除它并将列表传递给Test2或构造函数。
此外,Testing.employees应该在外面看
你可以像这样重新设计你的课程
public class Iterating
{
public void Test2(List<String> employees)
{
//This is where I am trying to iterate//
for (int i = 0; i < employees.Count; i++)
{
Console.WriteLine(employees[i]);
}
}
}
public class Testing
{
public List<String> Test1()
{
List<String> employees = new List<String>();//this should be outside the while loop
while (true)
{
Regex regex = new Regex(@"((.{5})-\d{2,5}-\d{2,5})|(@.*.com)");
Console.WriteLine("Please enter an e-mail");
string input = Console.ReadLine();
if(string.Equals(input, "quit", StringComparison.OrdinalIgnoreCase))
{
Console.WriteLine("You have quit the program");
break;
}
else if (match.Success)
{
Console.WriteLine(match.Value);//where is the match var
employees.Add(match.Value);//where is the match var
}
}
return employees;
}
}
public class Program
{
public static void Main()
{
Testing T1 = new Testing();
var employees = T1.Test1();
Iterating I1 = new Iterating();
I1.Test2(employees);
}
}