I am writing a small program to simulate a simple QS with failures. Due to his inexperience, he came across a problem almost from the very beginning. The code that I have and that does not work:

using System; using System.Collections.Generic; using System.Drawing; using System.Windows.Forms; namespace mmc { public partial class MainForm : Form { public MainForm() { InitializeComponent(); } void Button1Click(object sender, EventArgs e) { ServiceSystem mySystem = new ServiceSystem(260, 5, 4, 3); mySystem.Init(); } } public class ServiceSystem { public int RenderTime, // общее время моделирования ArrivalTime, // интервал поступления заявок ChannelCount, // количество каналов QueueCapacity; // размер очереди class Channel { internal int ProcessTime; // время обработки заявки bool isBusy; // занят? } class Queue { internal int Capacity, // размер очереди Occupied; // занятых мест bool isFull; // заполнена? } int RequestAll, // всего заявок RequestProcessed, // обработано заявок RequestRejected; // отклонено заявок public ServiceSystem(int _RenderTime, int _ArrivalTime, int _ChannelCount, int _QueueCapacity) { RenderTime = _RenderTime; ArrivalTime = _ArrivalTime; ChannelCount = _ChannelCount; QueueCapacity = _QueueCapacity; } public void Init() { List<string>[] Timeline = new List<string>[RenderTime]; // линия времени Channel[] ChannelArray = new Channel[ChannelCount]; // массив каналов for (int i = 0; i < RenderTime; i++) { Timeline[i] = new List<string>(); } for (int i = 0; i < ChannelCount; i++) { ChannelArray[i] = new Channel(); } foreach (Channel ch in ChannelArray) { ch.ProcessTime = 3; } Queue MainQueue = new Queue(); MainQueue.Capacity = QueueCapacity; // заполнить таймлайн посутплениями } void RequestAdd() { // } void RequestProcess() { // } void RequestReject() { // } public void Model() { foreach (List<string> str in Timeline) { // } } } 

}

It does not compile because of the first line of the Model() function and it’s clear why: Timeline was declared in another Init() function, but I can’t add an ad to the Timeline public declaration; you cannot access non-static fields ", but if you make the ServiceSystem fields static, the ServiceSystem constructor stops working.

    1 answer 1

    In your code, the List<string>[] Timeline is a local variable in the Init method. Make this array a member of the class.

     public class ServiceSystem { ... List<string>[] Timeline; public int RenderTime { get { return (Timeline == null)? 0 : Timeline.Length; } set { int oldLength = RenderTime; if (value == oldLength) return; List<string>[] old = Timeline; Timeline = new List<string>[value]; for (int i = 0; i < Math.Min(oldLength, Timeline.Length); i++) { Timeline[i] = old[i]; } for (int i = oldLength; i < Timeline.Length; i++) { Timeline[i] = new List<string>(); } } } public void Init() { ... } ... }