繁体   English   中英

如何创建一个我可以使用的类的实例是c#中的多个位置

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

所以我一直在研究一个详细介绍大学生的课程。 我有一个按钮,用于将详细信息设置为类的新实例,另一个用于检查学生是否通过我的类中的方法传递。 问题是我在第一个按钮中创建了一个类的实例,以便从用户输入的内容中添加值,但是我不能使用第二个按钮来访问在第一个按钮中创建的类的实例。

尝试通过类似方法创建属性

private Student student1 {get;set;}

然后,您可以使用在此属性中设置的实例

student1 = new Student();

如果您希望能够从此类外部访问该属性,则可以将其设置为公共,并且即使没有您实际使用的类的实例,也可以在该字段可访问时将其设置为静态(大多数可能是一种形式)。

那么,您当然不应该在另一个按钮中创建一个新学生。 当您将该属性设置为新学生时,您第一次设置的旧学生将会离开。

Static或Singleton类应该解决这个问题。 http://msdn.microsoft.com/en-us/library/ff650316.aspx-Singleton实现

更简单的方法也是类属性。 http://msdn.microsoft.com/en-us/library/w86s7x04.aspx - 类属性

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);

    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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