简体   繁体   中英

How can I create an instance of a class that I can use is more than one place in c#

So I've been working on a class that details students of a university. I have one button that sets the details to a new instance of a class, and another to check if the student passed, through a method in my Class. The problem is that I create an instance of a class in the first button to add the values from what the user input, but I cannot use the second button to access the instance of the class created in the first button.

Try to make a property over the method like

private Student student1 {get;set;}

Then you can work with the instance you set in this property with

student1 = new Student();

You can make it public if you want to be able to access the property from outside of this class, and you can also make it static when the field should be accessible even without having an instance of the class you're actually working in (most likely a form).

Then, you should of course not create a new Student in your other button. When you set the property to a new student, your old student that you set the first time will be gone.

Static or Singleton classes should solve this. http://msdn.microsoft.com/en-us/library/ff650316.aspx -Singleton implementation

The easier way are also class properties. http://msdn.microsoft.com/en-us/library/w86s7x04.aspx - Class properties

Student student1;  //**Simple Declare it here then**
private void button3_Click(object sender, EventArgs e)
    {

        student1 = new Student(); //**Create a new instance here**
        **//BUT You need to handle the exception that can come if the user clicks //button1   before button 3** possibly like this
         if(student1 == null)
                 return;
        label1.Text = student1.text();
        if (student1.hasPassed() == true)
        {
            passfailtextbox.Text = "Pass";
        }
        else
        {
            passfailtextbox.Text = "Fail";
        }
    }

private void button1_Click(object sender, EventArgs e)
    {
        Student student1 = new Student();
        student1.FirstName = firstnamebox.Text;
        student1.SecondName = secondnamebox.Text;
        student1.DateofBirth = DateTime.Parse(dobtextbox.Text).Date;
        student1.Course = coursetextbox.Text;
        student1.MatriculationNumber = int.Parse(matriculationtextbox.Text);
        student1.YearMark = double.Parse(yearmarktextbox.Text);

    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM