我想将一个非静态类的对象存储在另一个非静态类的静态字段中,并通过第二个类的属性访问它们。请帮帮我。
class Student
{
private string fullname;
private string course;
private string subject;
public Student(string fullname, string course)
{
this.fullname = fullname;
this.course = course;
}
public Student(string fullname, string course, string subject)
{
this.fullname = fullname;
this.course = course;
this.subject = subject;
}
public string FullName { get { return fullname; } set { fullname = value; }}
public string Course { get { return course; } set { course = value; }}
public string Subject { get { return subject; } set { subject = value;}}
}
class StudentData
{
private static Student bscStudent;
private static Student mscStudent;
public StudentData()
{
}
private static void GetStudentData()
{
Student student = new Student(" Isoboye Vincent", "IT");
Student student2 = new Student(" Doris Atuzie", "IT", "C#");
bscStudent= student;
mscStudent= student2;
}
public static Student BscStudent { get { return bscStudent; } set { bscStudent = value; } }
public static Student MscStudent { get { return mscStudent; } set { mscStudent = value; } }
}
class Program
{
static void Main(string[] args)
{
Console.WriteLine("List of students");
Console.WriteLine(StudentData.BscStudent);
Console.WriteLine(StudentData.MscStudent);
Console.ReadKey();
}
}
// Output:
//List of students
-
答案 0 :(得分:0)
现在我了解了问题所在,因此我提出了以下解决方案:
private static Student _BscStudent = null;
public static Student BscStudent {
get {
if (_BscStudent == null) {
_BscStudent = new Student(" Isoboye Vincent", "IT");
}
return _BscStudent;
}
set { _BscStudent = value; }
}
private static Student _MscStudent = null;
public static Student MscStudent {
get {
if (_MscStudent == null) {
_MscStudent = new Student(" Doris Atuzie", "IT", "C#");
}
return _MscStudent;
}
set {
_MscStudent = value;
}
}
我很长时间没有使用C#,所以我可能不记得一种更简单的方法。无论如何,从此解决方案开始,如果发现更好的方法,也许以后再重构该代码。