将结构改为类

本文关键字:结构 | 更新日期: 2023-09-27 17:51:13

我想将我的结构体Patient更改为一个类,但是当我做我的程序不工作(没有错误)时,我想将结构体Patient替换为类patientn,正如您可以看到我的按钮单击使用结构体Patient,我想将其更改为类并且仍然工作。我的程序:

public partial class Form1 : Form
{
    int itemCountInteger;
public struct Patient
{
    public string patientidstring;
    public string firstNameString;
    public string lastNameString;

}
public Form1()
{
    InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{

}

public class Patientn
{
    private int patientId;
    public string firstName;
    private string lastName;
    public Patientn()
    {
        patientId = 0;
        firstName = "";
        lastName = "";
    }
    public Patientn(int idValue, string firstNameVal, string lastNameVal)
    {
        patientId = idValue;
        firstName = firstNameVal;
        lastName = lastNameVal;
    }
}
//Array
Patient[] patientInfo = new Patient[10];
//this method is used to add items to array and display listbox
private void button1_Click(object sender, EventArgs e)
{
    try
    {
        foreach (Patient patientinfoIndex in patientInfo)
        patientInfo[itemCountInteger].patientidstring = textBox1.Text;
        patientInfo[itemCountInteger].firstNameString = textBox2.Text;
        patientInfo[itemCountInteger].lastNameString = textBox3.Text;
        string names = patientInfo[itemCountInteger].firstNameString + " " +                                                 patientInfo[itemCountInteger].lastNameString;
        listBox1.Items.Add(names);
        itemCountInteger++;
        listBox1.SelectedItem = names;
    }
    catch
    {
        MessageBox.Show("Contacts are limited to 20. Please delete some contacts prior to adding more.");
    }
}

将结构改为类

您应该显式地创建类实例

// It's quite enough since Patient is a struct
Patient[] patientInfo = new Patient[10];

如果Patientn,它应该是

// As it was...
Patientn[] patientInfo = new Patientn[10];
// You should add this since Patientn is a class
for (int i = 0; i < patientInfo.Length; ++i)
  patientInfo[i] = new Patientn();