全局数组无法读入控制台窗口c#

时间:2016-04-07 16:31:54

标签: c# arrays global

Schedule.cs

public static class SchArray
{

    public static string[] clientName = new string[20];
    public static DateTime[] startDate = new DateTime[20];
    public static DateTime[] endDate = new DateTime[20];
    public static string[] allocatedDriver = new string[20];
    public static string[] depot = new string[20];
    public static int count = 3;
}

public void schedule()
{

    SchArray.clientName[0] = "eric cartman";
    SchArray.clientName[1] = "peter griffin";
    SchArray.clientName[2] = "homer simpson";
    SchArray.startDate[0] = Convert.ToDateTime("2016,3,2");
    SchArray.startDate[1] = Convert.ToDateTime("2016,3,4");
    SchArray.startDate[2] = Convert.ToDateTime("2016,3,5");
    SchArray.endDate[0] = Convert.ToDateTime("2016,3,3");
    SchArray.endDate[1] = Convert.ToDateTime("2016,3,5");
    SchArray.endDate[2] = Convert.ToDateTime("2016,3,6");
    SchArray.allocatedDriver[0] = "owen";
    SchArray.allocatedDriver[1] = "daniel";
    SchArray.allocatedDriver[2] = "owen";
    SchArray.depot[0] = "depot1";
    SchArray.depot[1] = "depot2";
    SchArray.depot[2] = "depot3";
}

Work_Schedule.cs

public void schedule()
{

    Console.Clear();
    Console.WriteLine(" Create Work Schedule ");

    Console.WriteLine(Schedule.SchArray.clientName[0]);
    Console.ReadKey();
}

Console.WriteLine(Schedule.SchArray.clientName[0]);

^^^^^这一行应该显示eric cartman的名字,我已经调试了它,它说数组中没有对象,它们都是空的。

1 个答案:

答案 0 :(得分:0)

您需要创建一个Schedule对象,因为数组元素在构造函数中初始化:

   Schedule scheduleObject = new Schedule();
   Console.WriteLine(SchArray.clientName[0]);

对于这个特定场景,我想建议一种创建静态列表/对象数组的不同方法。我可以像下面这样修改类:

public class SchArray
    {
        public string clientName;
        public DateTime startDate;
        public DateTime endDate;
        public string allocatedDriver;
        public string depot;
        public int count = 3;
    }

我将List<SchArray>定义为静态;

public static List<SchArray> StaticSchArray = new List<SchArray>();

然后我可以填充列表,如下所示:

 StaticSchArray.Add(new SchArray() {clientName="eric cartman",
                               startDate=Convert.ToDateTime("2016,3,2"),
                               endDate= Convert.ToDateTime("2016,3,2"),
                               depot="depot1",allocatedDriver ="owen" });

同样,其他元素也可以添加到数组中。对于这种情况,这将是一个更好的选择。