C#中的对象初始化

Isu*_*uru 2 .net c# initialization object

当我声明如下:

class Professor
{
  string profid;
  public string ProfessorID
  {
     get { return profid;}
     set { profid=value;}
  }

  student st;

}


class student
{
  string name;
  string id;
  public string Name
  {
     get  { return name;}
     set  { name=value; } 
  }

 public string StudentID
 {
   get { return id;}
   set { id=value; }
 }

}


public void GetDetails()
{
  Professor prf=new Professor(){ ProfessorID=1, how to initialize student here?};

}
Run Code Online (Sandbox Code Playgroud)

在GetDetails()里面我如何初始化学生?

Mar*_*ell 5

首先让它可访问:

public student Student { get; set; }
Run Code Online (Sandbox Code Playgroud)

然后像:

Professor prf = new Professor()
{
    ProfessorID = "abc",
    Student = new student { Name = "Marc", StudentID = "def" }
};
Run Code Online (Sandbox Code Playgroud)

请注意,如果属性是get-only:

private readonly student _student = new student();  
public student Student { get { return _student; }}
Run Code Online (Sandbox Code Playgroud)

然后,您可以使用替代语法(设置属性而不尝试更改学生参考):

Professor prf = new Professor()
{
    ProfessorID = "abc",
    Student = { Name = "Marc", StudentID = "def" }
};
Run Code Online (Sandbox Code Playgroud)