В настоящее время я создаю программу симулятора планирования ЦП для своего школьного проекта. В настоящее время я стою с ошибкой:
CS0122 Form1.AvgWaiting недоступен из-за его уровня защиты
И когда я изменяю TextBox на общедоступный из Form1Designer.cs, я получаю следующую ошибку:
CS0120 C# Для нестатического поля, метода или свойства требуется ссылка на объект.
У меня есть Form1.cs и отдельный класс для моих алгоритмов. Я буду использовать свои алгоритмы для отображения вывода для моего представления данных и текстового поля.
Моя форма1.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace CPU_Scheduling_Simulator
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
// set default values to comboBox
foreach (Control cont in this.Controls)
{
if (cont is ComboBox)
{
((ComboBox)cont).SelectedIndex = 0;
}
}
}
public void Form1_Load(object sender, EventArgs e)
{
}
public void groupBox2_Enter(object sender, EventArgs e)
{
}
public void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
}
public void button1_Click(object sender, EventArgs e)
{
Close();
}
public void buttonGenerate_Click(object sender, EventArgs e)
{
dataGridView1.Rows.Clear();
int count = int.Parse(comboBoxProcess.GetItemText(comboBoxProcess.SelectedItem));
if (comboBoxProcess.SelectedIndex == -1)
MessageBox.Show("Please select num of Process");
else
{
dataGridView1.Rows.Add(count);
for (int i = 0; i < count; i++)
{
dataGridView1.Rows[i].Cells["Processes"].Value = "" + (i+1);
}
}
}
public void buttonClear_Click(object sender, EventArgs e)
{
foreach (Control control in this.Controls)
{
if (control is TextBox)
((TextBox)control).Text = null;
}
dataGridView1.Rows.Clear();
}
public void groupBox5_Enter(object sender, EventArgs e)
{
}
public void buttonSimulate_Click(object sender, EventArgs e)
{
int count = int.Parse(comboBoxProcess.GetItemText(comboBoxProcess.SelectedItem));
int index = comboBoxAlgorithm.SelectedIndex;
switch (index)
{
case 0:
// Process id's
int[] processes = new int[count];
int n = processes.Length;
// Burst time of all processes
int[] burst_time = new int[n];
for (int x = 0; x < n; x++)
burst_time[x] = int.Parse((string)dataGridView1.Rows[x].Cells["BurstTime"].Value);
// Arrival time of all processes
int[] arrival_time = new int[n];
for (int x = 0; x < n; x++)
arrival_time[x] = int.Parse((string)dataGridView1.Rows[x].Cells["ArrivalTime"].Value);
FCFS.findavgTime(processes, n, burst_time, arrival_time);
break;
default:
MessageBox.Show("Please select an Algorithm");
break;
}
}
}
}
Мой FCFS.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace CPU_Scheduling_Simulator
{
public class FCFS
{
// Function to find the waiting time for all
// processes
public static void findWaitingTime(int[] processes, int n, int[] bt, int[] wt, int[] at)
{
int[] service_time = new int[n];
service_time[0] = 0;
wt[0] = 0;
// calculating waiting time
for (int i = 1; i < n; i++)
{
// Add burst time of previous processes
service_time[i] = service_time[i - 1] + bt[i - 1];
// Find waiting time for current process =
// sum - at[i]
wt[i] = service_time[i] - at[i];
// If waiting time for a process is in negative
// that means it is already in the ready queue
// before CPU becomes idle so its waiting time is 0
if (wt[i] < 0)
wt[i] = 0;
}
}
// Function to calculate turn around time
public static void findTurnAroundTime(int[] processes, int n, int[] bt,
int[] wt, int[] tat)
{
// Calculating turnaround time by adding bt[i] + wt[i]
for (int i = 0; i < n; i++)
tat[i] = bt[i] + wt[i];
}
// Function to calculate average waiting and turn-around
// times.
public static void findavgTime(int[] processes, int n, int[] bt, int[] at)
{
int[] wt = new int[n]; int[] tat = new int[n];
// Function to find waiting time of all processes
findWaitingTime(processes, n, bt, wt, at);
// Function to find turn around time for all processes
findTurnAroundTime(processes, n, bt, wt, tat);
// Display processes along with all details
//Console.Write("Processes " + " Burst Time " + " Arrival Time "
// + " Waiting Time " + " Turn-Around Time "
// + " Completion Time \n");
int total_wt = 0, total_tat = 0;
for (int i = 0; i < n; i++)
{
total_wt = total_wt + wt[i];
total_tat = total_tat + tat[i];
int compl_time = tat[i] + at[i];
//Console.WriteLine(i + 1 + "\t\t" + bt[i] + "\t\t"
// + at[i] + "\t\t" + wt[i] + "\t\t "
// + tat[i] + "\t\t " + compl_time);
Form1.dataGridView1.Rows[i].Cells["Processes"].Value = i + 1;
Form1.dataGridView1.Rows[i].Cells["BurstTime"].Value = bt[i];
Form1.dataGridView1.Rows[i].Cells["ArrivalTime"].Value = at[i];
Form1.dataGridView1.Rows[i].Cells["WaitingTime"].Value = wt[i];
}
//Console.Write("Average waiting time = "
// + (float)total_wt / (float)n);
//Console.Write("\nAverage turn around time = "
// + (float)total_tat / (float)n);
Form1.AvgWaiting.Text = ""+(float)total_wt / (float)n);
Form1.AvgTurnaround.Text ""+(float)total_tat / (float)n);
}
// Driver code
}
}
Также кто-нибудь может связать меня с работающей диаграммой Ганта и готовым исходным кодом очереди на С#, чтобы я мог его изучить. Я нашел один на YouTube, но он на Java ссылка
Кстати, большое спасибо за помощь такому новичку, как я. Я знаю, что мне нужно многому научиться, и мне было легче учиться со всей вашей помощью.
спасибо, user9938, я прочитал об этом здесь из другого сообщения пользователя, но не совсем понял. Не могли бы вы связать меня с некоторыми ресурсами, где я мог бы узнать больше об этих свойствах? Спасибо
Вот сообщение: stackoverflow.com/questions/6709072/c-getter-setter
Form1 — это имя класса, а не экземпляр этого класса. Если вы хотите сослаться на существующий экземпляр, вам нужно передать экземпляр там, где это необходимо, или получить его из коллекции Application.OpenForms.
Так, например, вы можете написать это перед использованием Form1
var f1 = Application.OpenForms.OfType<Form1>().FirstOrDefault();
if (f1 != null)
{
// use f1 wherever you use Form1.
}
это будет работать, если у вас открыт только один экземпляр Form1 в тот же период времени. Если у вас более одного экземпляра, вам необходимо передать экземпляр текущей формы Form1 методу FCFS.
FCFS.findavgTime(processes, n, burst_time, arrival_time, this);
break;
и
public static void findavgTime(int[] processes, int n, int[] bt, int[] at, Form1 f1)
{
// and again use f1 instead of Form1
Спасибо, почти исправил. Я только имею; и } ожидаемая ошибка с кодом ниже: f1.AvgWaiting.Text = ""+(float)total_wt / (float)n); f1.AvgTurnaround.Text = ""+(float)total_tat / (float)n);
Я только что заметил, что он отсутствует (.
Используйте свойства. В FCFS:
public static System.Windows.Forms.DataGridView DataGridView1 {get; set; }
.public static Decimal AvgWaiting { get; set; }
, ...