当我有这样的声明时:
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?};
}
在 GetDetails() 中我如何初始化学生?
最佳答案
首先使其可访问:
public student Student { get; set; }
然后是这样的:
Professor prf = new Professor()
{
ProfessorID = "abc",
Student = new student { Name = "Marc", StudentID = "def" }
};
请注意,如果该属性是只获取的:
private readonly student _student = new student();
public student Student { get { return _student; }}
然后您可以使用替代语法(设置属性而不尝试更改学生引用):
Professor prf = new Professor()
{
ProfessorID = "abc",
Student = { Name = "Marc", StudentID = "def" }
};
关于c# - C#中的对象初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1584270/