简体   繁体   中英

How do I set value into deep properties of the Student class?

I am still new to C#. So below is my Student class

class Student
{
    public partial class Document
    {
        private StudentBio studentBio;
        public StudentBio StudentBio{get;set;}
    }
    public partial class StudentBio
    {
        private StudentCourse[] studentCourse;
        public StudentCourse[] StudentCourse{get;set;}
    }

    public partial class StudentCourse
    {
        private string courseId;
        private string courseName;
        public string CourseName{get;set;}
    }
}

How do I set the courseId since I got error when setting the value into the field. I could not access directly like Document.StudentBio.StudentCourse.CourseId to set the value.

public static void Main()
{   
    Student myObject = new Student();
    Type myType = typeof(Student);
    FieldInfo myFieldInfo = myType.GetField("courseId", 
        BindingFlags.NonPublic | BindingFlags.Instance); 
    Console.WriteLine(myFieldInfo);
}

There is no need Reflection to set a deep property. Not sure why are you making this much hierarchy , but you can solve your issue by doing following.

You must have to initialize the property in Constructor of each class to avoid NUllReferenceExecption

public class Student
{
    public Student()
    {
        StudentDoc = new Document();
    }
   public Document StudentDoc { get; set; }

}
public class Document
{
    public Document()
    {
        StudentBio = new StudentBio();
    }
    public StudentBio StudentBio { get; set; }
}
public class StudentBio
{
    public StudentBio()
    {
        StudentCourse = new StudentCourse();
    }
    public StudentCourse StudentCourse { get; set; }
}
public class StudentCourse
{
    public string CourseId { get; set; }
    public string CourseName { get; set; }
}

And from Main

public static void Main()
{ 
        Student myObject = new Student();          
        myObject.StudentDoc.StudentBio.StudentCourse.CourseId = "10";
}

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