質問

I want to change my struct Patient to a class but when I do my program don't work(free of errors) I want to substitute the struct patient for class patientn, as you can see my button click uses the struct patient and I want to change it for a class and still work. visual studio 10 My program:

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.");
    }

}
役に立ちましたか?

解決

You should explicitly create class instances. In your case

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

In case of Patientn that is class it should be

// 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();
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top